Why does printf print wrong values?

浪子不回头ぞ 提交于 2019-12-28 03:06:09

问题


Why do I get the wrong values when I print an int using printf("%f\n", myNumber)?

I don't understand why it prints fine with %d, but not with %f. Shouldn't it just add extra zeros?

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

回答1:


well of course it prints the "weird" stuff. You are passing in ints, but telling printf you passed in floats. Since these two data types have different and incompatible internal representations, you will get "gibberish".

There is no "automatic cast" when you pass variables to a variandic function like printf, the values are passed into the function as the datatype they actually are (or upgraded to a larger compatible type in some cases).

What you have done is somewhat similar to this:

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 */



回答2:


If you want to print them as floats, you can cast them as float before passing them to the printf function.

printf("%f %f %f %f %f\n", (float)a, (float)b, (float)c, (float)d, (float)e);



回答3:


a, b, c, d and e aren't floats. printf() is interpreting them as floats, and this would print weird stuff to your screen.




回答4:


Using incorrect format specifier in printf() invokes Undefined Behaviour

For example:

 int n=1;
 printf("%f", n); //UB

 float x=1.2f;
 printf("%d", x); //UB

 double y=12.34;
 printf("%lf",y); //UB 

Note: format specifier for double in printf() is %f.




回答5:


the problem is... inside printf. the following happens

if ("%f") {
 float *p = (float*) &a;
 output *p;  //err because binary representation is different for float and int
}



回答6:


the way printf and variable arguments work is that the format specifier in the string e.g. "%f %f" tells the printf the type and thus the size of the argument. By specifying the wrong type for the argument it gets confused.

look at stdarg.h for the macros used to handle variable arguments




回答7:


For "normal" (non variadac functions with all the types specified) the compiler converts integer valued types to floating point types where needed.

That does not happen with variadac arguments, which are always passed "as is".



来源:https://stackoverflow.com/questions/3655250/why-does-printf-print-wrong-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!