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

后端 未结 7 1384
耶瑟儿~
耶瑟儿~ 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:47

    No floating point numbers has an exact representation, they all have limited accuracy. When converting from a number in text to a float (with scanf or otherwise), you're in another world with different kinds of numbers, and precision may be lost. Same thing goes when converting from a float to a string: you decide on how many digits you want. You can't know "how many digits there are" in a float before converting to text or another format that can keep that information. This all has to do with how floats are stored:

    significant_digits * baseexponent

提交回复
热议问题