printing the integral part of a floating point number

后端 未结 7 531
不知归路
不知归路 2021-01-13 23:03

I am trying to figure out how to print floating point numbers without using library functions. Printing the decimal part of a floating point number turned out to be quite ea

7条回答
  •  耶瑟儿~
    2021-01-13 23:34

    Like Agent_L's answer, you're suffering from the false result caused by dividing the value by 10. Float, like any binary floating point type, cannot express correctly most rational number in decimal. After division, most of the case the result cannot be fitted into binary, so it'll be rounded. Hence the more you divide, the more error you'll realize.

    If the number is not very large, a quick solution would be multiplying it with 10 or a power of 10 depending on how many digits after decimal point you need.

    Another way was described here

提交回复
热议问题