How does this program work?

前端 未结 13 2145
闹比i
闹比i 2020-11-30 22:44
#include 

int main() {
    float a = 1234.5f;
    printf(\"%d\\n\", a);
    return 0;
}

It displays a 0!! How is that

13条回答
  •  隐瞒了意图╮
    2020-11-30 23:21

    The %d specifier tells printf to expect an integer. So the first four (or two, depending on the platform) bytes of the float are intepreted as an integer. If they happen to be zero, a zero is printed

    The binary representation of 1234.5 is something like

    1.00110100101 * 2^10 (exponent is decimal ...)
    

    With a C compiler which represents float actually as IEEE754 double values, the bytes would be (if I made no mistake)

    01000000 10010011 01001010 00000000 00000000 00000000 00000000 00000000
    

    On an Intel (x86) system with little endianess (i.e. the least significant byte coming first), this byte sequence gets reversed so that the first four bytes are zero. That is, what printf prints out ...

    See This Wikipedia article for floating point representation according to IEEE754.

提交回复
热议问题