Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

c - Why does printf print wrong values?

Why do I get the wrong values when I print an int using printf("%f ", 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
", a, b, c, d, e);   //prints fine
printf("%f %f %f %f %f
", a, b, c, d, e);   //prints weird stuff
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", x.f); /* pass in the binary representation for 10, 
                        but treat that same bit pattern as a float, 
                        even though they are incompatible */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...