Why does printf print wrong values?

后端 未结 7 1478
情歌与酒
情歌与酒 2020-12-01 22:19

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

7条回答
  •  生来不讨喜
    2020-12-01 23:12

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

提交回复
热议问题