Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

printf - Printing int as float in C

I'm using Visual Studio TC compiler for Little Endian. The following is the piece of code:

void main()
{    
    float c = 1.0;
    int a = 0x3F800000;
    int *ptr = (int *)&c;
    printf("
0x%X
", *ptr);
    printf("
a = %f", a);
    printf("
c = %f", c);
    return;    
}

The output is:

0x3F800000
a = 0.000000
c = 1.000000

Float value 1.0 is 0x3F800000 and stored as 00 00 80 3F in memory for Little Endian. The same value is assigned to int a. How printf prints 0.000000 for int a while 1.000000 for float c? I've seen it prints all integer values as 0.000000, when printed using %f in printf.

Also, since printf is variable argument function, how does it knows whether the passed value in the register is int or float?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My psychic powers tell me Adam Liss's comment is the right answer: float arguments are promoted to double, so the printf() function expects that to happen: It expects a 64-bit value on the stack, but gets 32 bits plus garbage data that happen to be zero.

If you increase the display precision, the display should be something like a = 0.00000000001.

This also means this should work:

void main()
{    
    double c = 1.0;
    long long a = 0x3FF0000000000000;
    long long *ptr = (long long *)&c;
    printf("
0x%llX
", *ptr);
    printf("
a = %f", a);
    printf("
c = %f", c);
    return;    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...