简体   繁体   English

为什么printf打印不正确的值?

[英]Why does printf print the incorrect value?

The following code always prints "0.00" . 以下代码始终显示"0.00" I was expecting "7888" . 我期待的是"7888" Should I convert it to double ? 我应该将其转换为double吗?

long l = 7888;
printf("%.2f", l);

%.2f is not a valid format for a long . %.2f long不是有效格式。 You can cast it to double: 您可以将其转换为两倍:

long l = 7888;
printf("%.2f", (double)l);

Here is a table (scroll a bit down) where you can see which codes are allowed for all number types. 是一张表格(向下滚动),您可以在其中查看所有数字类型允许使用的代码。

%f expects a double and l variable is a long. %f期望doublel变量是long。 printf() does not convert it's arguments to a type required by the format specifier all-by-itself magically. printf()不会神奇地自行将其参数转换为格式说明符所需的类型。

FWIW, printf() being a variadic function , default argument promotion rule is applied on the supplied arguments, and it does not change a long to double , either. FWIW, printf()可变函数 ,默认的参数提升规则应用于提供的参数,并且不会将long更改为double If at all, you want that conversion to happen, you have to cast the argument value explicitly. 如果完全希望发生这种转换,则必须显式强制转换参数值。

You need to write something like 你需要写一些像

printf("%.2f", (double)l);

Please note, this code invokes undefined behaviour , without an explicit cast. 请注意,此代码将调用未定义的行为 ,而不进行显式强制转换。 Reference, C11 , chapter §7.21.6.1, fprintf() 参考, C11 ,第§7.21.6.1章, fprintf()

[....] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. [....]如果任何参数不是对应转换规范的正确类型,则行为未定义。

The %f format specifier expects a double , but you're passing it a long , so that's undefined behavior. %f格式说明符期望double ,但是您要传递long ,所以这是未定义的行为。

If you want to print it properly, you need to either use the %ld format specifier to print it as a long : 如果要正确打印,则需要使用%ld格式说明符将其打印为long格式:

printf("%ld", l);

Or cast l to double to print it as a floating point number: 或将ldouble以将其打印为浮点数:

printf("%.2f", (double)l);
 I was expecting "7888". 

This happens because you are trying to print LONG with FLOAT identifier. 发生这种情况是因为您尝试使用FLOAT标识符打印LONG。 The compiler complains about that if you turn your setting on: 如果您打开设置,编译器会抱怨:

 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? 

By the way you can cast it too, if this is what you really need. 顺便说一句,如果您确实需要,也可以进行转换。

I think this is what you realy need: 我认为这是您真正需要的:

#include<stdio.h>

int main(void){
    long l = 7888;
    printf("%ld", l);
    return 0;
}

7888 7888

You cannot printf a long proberly with a float identifier. 您不能使用浮点标识符长时间打印。 What do you want do achieve? 您想要实现什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM