printf指定float的整数格式字符串
#include int main() { float a = 5; printf("%d", a); return 0; }
这给出了输出:
0
为什么输出为零?
它不打印5,因为编译器不知道自动转换为整数。 你需要自己做(int)a
。
也就是说,
#include void main() { float a=5; printf("%d",(int)a); }
正确输出5。
比较该程序
#include void print_int(int x) { printf("%d\n", x); } void main() { float a=5; print_int(a); }
由于print_int
的声明,编译器直接知道将float转换为int。
%d
格式说明符只能与int
类型的值一起使用。 你正在传递一个double
( float
将被隐式转换为)。 结果行为未定义。 没有回答“为什么打印0?” 题。 什么都可以打印。 事实上,任何事情都可能发生。
PS
- 这是
int main
,而不是void main
。 - 标准C中没有
conio.h
这样的标题。
您应该将其强制转换为int以使用%d,或使用格式字符串显示不带小数精度的float:
void main() { float a=5; printf("%d",(int)a); // This casts to int, which will make this work printf("%.0f",a); // This displays with no decimal precision }
您需要使用%f
而不是%d
– %d
仅用于整数,而%f
用于浮点:
#include #include void main() { float a=5; printf("%f",a); }
您必须使用不同的格式化字符串,只需查看http://www.cplusplus.com/reference/clibrary/cstdio/printf/
printf(“%f”,a);
您将要使用%f来打印浮点值。
例如
float a=5; printf("%f",a);
正如其他人所说,你需要在格式字符串中使用%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' $
哦,还有一件事:你应该在printf()
包含’\ n’以确保输出被发送到输出设备。
printf("%d\n", a); /* ^^ */
或使用fflush(stdout);
在printf()
。