Original: http://purec.binghua.com/Article/class1/class2/200411/368.html
I received a letter today, I put forward such a meaningful problem #include
INT main () {Printf ("% d / n", POW (4, 2));
The output is 0, but
#include
INT main () {Int a = POW (4, 2); Printf ("% D / N, A);}
The output is correct. Why?
This problem is very interesting. In fact, if the first program is changed, change to Printf ("% d / n", (int) POW (4, 2)); then the output of the first problem is also correct.
Compare two kinds of ways, you can find that the problem is to calculate the value of the POW (4, 2) first in one conversion, and then convert it into an int type value, and finally use% D output is correct, this main Because Printf () does not perform type conversion when passing the parameters, and the return value of the POW () is a Double type value!
We calculate the POW (4, 2), its result is 16, then we use the Double type to indicate that the 16 Double type is expressed as: 0 0 0 0 0 0 30 40, then put all of them all stack The 4b close to the top of the stack is 0 0 0 and the compiler calls the printf () function, and the printf () is analyzed to control the string, and it is found that the% d, it thinks the parameters in the stack (4b), so it Just take it out of the 4B to display, the result is 0 ~~,
Therefore, it is necessary to get Printf () know the parameters of Double (8B), so we should use: "% f" instead of "% D" to output POW () value.
About Printf () to the parameters, you can see the related articles in the << Pure C Forum · Electronic Magazine (Phase II).