![](/img/trans.png)
[英]Why does printf print random value with float and integer format specifier
[英]Why does printf print the incorrect value?
以下代码始终显示"0.00"
。 我期待的是"7888"
。 我应该将其转换为double
吗?
long l = 7888;
printf("%.2f", l);
%.2f
long
不是有效格式。 您可以将其转换为两倍:
long l = 7888;
printf("%.2f", (double)l);
这是一张表格(向下滚动),您可以在其中查看所有数字类型允许使用的代码。
%f
格式说明符期望double
,但是您要传递long
,所以这是未定义的行为。
如果要正确打印,则需要使用%ld
格式说明符将其打印为long
格式:
printf("%ld", l);
或将l
为double
以将其打印为浮点数:
printf("%.2f", (double)l);
I was expecting "7888".
发生这种情况是因为您尝试使用FLOAT标识符打印LONG。 如果您打开设置,编译器会抱怨:
program.c:5:5: error: format '%f' expects argument of type 'double', but argument 2 has type 'long int' [-Werror=format=] printf("%f", l); ^ cc1: all warnings being treated as errors
。
Should I convert it to double?
顺便说一句,如果您确实需要,也可以进行转换。
我认为这是您真正需要的:
#include<stdio.h>
int main(void){
long l = 7888;
printf("%ld", l);
return 0;
}
7888
您不能使用浮点标识符长时间打印。 您想要实现什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.