Original article: http://purec.binghua.com/Article/Class1/Class2/200411/368.html
Today, I received a letter asking such an interesting question.
# Include <math. h>
# Include <stdio. h>
Int main ()
{
Printf ("% d/N", POW (4, 2 ));
}
The output is 0,
However
# Include <math. h>
# Include <stdio. h>
Int main ()
{
Int A = POW (4, 2 );
Printf ("% d/N, );
}
The output is correct. Why?
This problem is very interesting. In fact, if you change the first program
Printf ("% d/N", (INT) Pow (4, 2 ));
The output of the first question is correct.
By comparing the two methods, we can find that the problem is that under a conversion, we first calculate the value of POW (), and then convert it to an int value, finally, use % d for output. This is mainly because printf () does not convert the type when passing the parameter, and the return value of POW () is a double value!
Let's calculate POW (4, 2). The result is 16. Then, we use the double type to represent it,
We can see that the double type of 16 is: 0 0 0 0 0 30 40
Then, press all of them on the stack, so the 4B close to the top of the stack is 0 0 0 0
Then the compiler calls the printf () function. When printf () analyzes and controls the string and finds whether it is % d, it considers the parameter in the stack to be an integer (4B ), so it only gets the expected 4B for display, so the result is 0 ~~,
Therefore, to get the correct result, we need to let printf () know that the stack is a double (8B) parameter. Therefore, we should use:
"% F" instead of "% d" to output the value of POW.
For more information about how printf () processes parameters, see <pure C Forum · e-Magazine> (Issue 2.