为了账号安全,请及时绑定邮箱和手机立即绑定

printf为浮点数指定整数格式的字符串

printf为浮点数指定整数格式的字符串

C
ABOUTYOU 2019-12-06 10:30:31
#include <stdio.h>int main(){    float a = 5;    printf("%d", a);    return 0;}这给出了输出:0为什么输出为零?
查看完整描述

3 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

它不会打印5,因为编译器不知道会自动转换为整数。你需要(int)a自己做。


也就是说,


#include<stdio.h>

void main()

{

float a=5;

printf("%d",(int)a);

}

正确输出5。


将该程序与


#include<stdio.h>

void print_int(int x)

{

printf("%d\n", x);

}

void main()

{

float a=5;

print_int(a);

}

由于的声明,编译器直接知道将float转换为int的位置print_int。


查看完整回答
反对 回复 2019-12-06
?
倚天杖

TA贡献1828条经验 获得超3个赞

正如其他人所说,您需要使用%f格式字符串或将其转换a为int。


但我想指出的是,您的编译器可能知道printf()的格式字符串,并且可以告诉您您使用的格式错误。经过适当调用(-Wall包括-Wformat)的我的编译器说:


$ /usr/bin/gcc -Wformat tmp.c

tmp.c: In function ‘main’:

tmp.c:4: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘double’


$ /usr/bin/gcc -Wall tmp.c

tmp.c: In function ‘main’:

tmp.c:4: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘double’


$

哦,还有另一件事:您应该在中包含'\ n',printf()以确保将输出发送到输出设备。


printf("%d\n", a);

/*        ^^ */

或fflush(stdout);在printf()。之后使用。


查看完整回答
反对 回复 2019-12-06
  • 3 回答
  • 0 关注
  • 543 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信