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

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);

Here 是一个 table(稍微向下滚动),您可以在其中查看所有数字类型都允许使用哪些代码。

您不能打印带有浮点标识符的 long proberly。你想达到什么目的?

%f 期望 doublel 变量是长整数。 printf() 不会神奇地将它的参数转换为格式说明符 all-by-itself 所需的类型。

FWIW,printf()variadic function,默认参数提升规则应用于提供的参数,它不会将 long 更改为 double,或者.如果您希望发生这种转换,则必须明确地 cast 参数值。

你需要这样写

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

请注意,此代码调用 undefined behaviour,没有 显式 转换。参考,C11,章节 §7.21.6.1,fprintf()

[....] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

%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