Why is printf printing wrong values?

Why am I getting the wrong values ​​when printing intwith printf("%f\n", myNumber)?

I don’t understand why it prints fine with %d, but not with %f. Shouldn't he 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
+3
source share
7 answers

Well, of course, he prints "weird" things. You pass in ints but report printfwhich you passed in floats. Since these two types of data have different and incompatible internal representations, you will get "nonsense."

, ​​ 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 */
+12

float, float, printf.

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

a, b, c, d e . printf() float, .

+3

printf() Undefined Behaviour

:

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

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

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

: double printf() %f.

+2

... printf.

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

printf , , . "% f% f" printf , , . , .

stdarg.h ,

0

"" ( ) .

This does not happen with variadac arguments, which are always passed as-is.

0
source

Source: https://habr.com/ru/post/1763531/


All Articles