C++ floating point accuracy in while loops

前端 未结 4 444
暖寄归人
暖寄归人 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 05:01

    Binary floating point numbers cannot, in general, represent fractional decimal values, even if the total number of decimals is small. For example, 0.1 cannot be represented exactly.

    To deal with exact values different approaches exist which all amount to using a different base than 2. Depending on tge specific needs the approaches are more or less involved. The easieast approach for your case is to use a fixed precision instead of a variable precision. To compute with fixed precision you'd just use an integer which represents the value you actually want multiplied by a suitable power of 10. Depending on the amount of computations you do you can either package the logic into a class or distribute it throughout the code. In a "real" application I'd package it into a class, in an assignment (homework, interview, etc.) I'd probably just apply the logic directly to an int.

提交回复
热议问题