简体   繁体   中英

Unexpected double value output when using printf

#include <stdio.h>
int main()
{
    double  a=7.1;
    printf("%d",a);
    return 0;
}

Output:

1717986918

When I am writing this program and using signed format specifiers to the method printf() . Why I am getting this value?

Its a format specifier problem.
Using "%d" , the compiler is being told that the type of data being printed is of type int , but the variable is of type float , causing undefined behavior , resulting in this case, the value 1717986918 .

The format specifier for type float is "%f" , not "%d" .

Change this:

printf("%d",a);

To this:

printf("%f",a);

If you compile with -Wall or equivalent in your compiler settings, a warning for this will notify you.

Your code has undefined behavior. It's not defined what should be the output of your code and as far as any programmer should be concerned, your code spawns nasal demons .

why I am getting this output in my Cprogram?

I am assuming lot about your computer and compiler implementation, such as that your compiler uses IEEE754 standard to represent floating point numbers and the size of an int is 4 bytes and that your computer uses little endian. According to this site the double number 7.1 when represented as a IEEE754 double precision number is stored as 8 bytes as a 0x401C666666666666 number. Then those bytes are passed to printf as variadic arguments. Because of how on your architecture arguments are passed, the least significant 4 bytes from that number are extracted for printf %d format specifier, which results in printing the base 10 representation of 0x66666666 number, which is 1717986918 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM