为什么printf打印错误的值?

use*_*514 5 c printing printf type-conversion

打印int使用时为什么会出现错误的值printf("%f\n", myNumber)

我不明白为什么它打印好%d,但不是%f.它不应该只是添加额外的零?

int a = 1;
int b = 10;
int c = 100;
int d = 1000;
int e = 10000;

printf("%d %d %d %d %d\n", a, b, c, d, e);   //prints fine
printf("%f %f %f %f %f\n", a, b, c, d, e);   //prints weird stuff
Run Code Online (Sandbox Code Playgroud)

Eva*_*ran 15

当然它打印出"怪异"的东西.你是在传球int,但是告诉printf你传球float.由于这两种数据类型具有不同且不兼容的内部表示,因此您将获得"乱码".

将变量传递给varndic函数时没有"自动转换" printf,这些值作为它们实际的数据类型传递给函数(或者在某些情况下升级为更大的兼容类型).

你所做的有点类似于:

union {
    int n;
    float f;
} x;

x.n = 10;

printf("%f\n", x.f); /* pass in the binary representation for 10, 
                        but treat that same bit pattern as a float, 
                        even though they are incompatible */
Run Code Online (Sandbox Code Playgroud)

  • *"当你将变量传递给一个变量函数时,没有"自动投射""* - 这是关键,我认为这是重复的,因为它非常微妙(如果你来自更高级别的语言)并且很重要. (5认同)