C++ floating point accuracy in while loops

前端 未结 4 441
暖寄归人
暖寄归人 2021-01-23 04:10

I am trying to count the amount of dollar and coin denominations in a grand total by using a series of while loops. When I get down to the coins however, I am off by a penny. Wh

4条回答
  •  走了就别回头了
    2021-01-23 04:47

    Don't use floating point in cases where you need exact values. 99.95 can't be exactly represented in a float or double, a bit like 1/3 can't be exactly represented using a finite number of normal decimal digits.

    As Doug T. suggested, you can use an integer to hold the number of pennies. When the user types 123.45, read it as two integers, and then store it as 12345 pennies, not as 123.45 dollars.

    In this case, you can also try to change your last while (amount >= .01) to something like while (amount >= .005). It's not a solution that can be generally recommended, and if this is a real-life bank application you really should avoid it, but it will help against at least some of the errors.

提交回复
热议问题