Why does a C floating-point type modify the actual input of 125.1 to 125.099998 on output?

后端 未结 7 1359
耶瑟儿~
耶瑟儿~ 2020-12-12 05:07

I wrote the following program:

 #include
    int main(void)
    {
     float f;
     printf(\"\\nInput a floating-point no.: \");
     scanf(\         


        
相关标签:
7条回答
  • 2020-12-12 05:57

    Think about a fixed point representation first.

    2^3=8 2^2=4 2^1=2 2^0=1 2^-1=1/2 2^-2=1/4 2^-3=1/8 2^-4=1/16

    If we want to represent a fraction then we set the bits to the right of the point, so 5.5 is represented as 01011000.

    But if we want to represent 5.6, there is not an exact fractional representation. The closest we can get is 01011001 == 5.5625

    1/2 + 1/16 = 0.5625

    2^-4 + 2^-1

    0 讨论(0)
提交回复
热议问题