Question about how to use % d output in printf () for POW ()

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.