Question of printf, printf

Source: Internet
Author: User

Question of printf, printf

I used to implement printf when I learned the book "write an operating system by myself" by yuan, but it is a relatively simple version. I recently read the programmer interview book to answer this question:
# Include <stdio. h>
Int main {
Printf ("% f", 5 );
Printf ("% d", 5.01 );
}

What is the output?
The question is not difficult but very detailed: The first output is 0.000000, because the printf function encounters % f and considers the parameter as a double type (float in the printf function is automatically converted to a double type ), 5 is an int type with only four digits, so the output takes 8 digits out of bounds and outputs 0.000000. The second output takes only four digits and outputs a large number.

So I thought: What Will printf ("% f % d", 5, 5.01 );

In fact, both outputs are large numbers, but there are many zeros behind the first output floating point number, and the second output is the same as the second output.

Reasons for personal opinion analysis:

First, the stack grows down, while the printf function (in fact, all functions) parameters go to the stack from the right to the left. Then 5.01 first goes to the stack, and 5 re-enters, that is, 5.01 is at the high address, 5 at the low address, when % f is output, take all the bits of 5 and the four low byte of 5.01, output a large number, output % d to take the high byte, also output a large number. Http://hovertree.com/menu/c/
To intuitively see this analysis:
We use the following statement for testing:

Printf ("% f % d", 5,120.5 );

120.5 of the storage formats are as follows:

0 100 0000 0101 1110 0010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
4-byte values are all 0, and 4-byte values are large numbers,
Therefore, the output should be 0.000000 and a large number.
The actual output is as follows:

Recommended: http://www.cnblogs.com/roucheng/p/cfenge.html

Related Article

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.