Comparing currency values as floats does not work

后端 未结 4 1244
忘了有多久
忘了有多久 2020-12-12 04:54

If I type 0.01 or 0.02 the the program just exits immediately. What do I do?

#include 

char line[100];
float amount;

int main()
{
printf(\"E         


        
4条回答
  •  离开以前
    2020-12-12 05:26

    Firstly, do not attempt to compare doubles, or to compare floats, or to compare doubles to floats (exception: comparing against 0 is OK, and arguably all integers). Other answers have given good links as to why, but I especially liked: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

    Secondly, if you are dealing with an amount of money, don't use doubles, or get out of double as quickly as possible. Either use a fixed point library (a bit complex for what you want), or simply do:

    int cents = (int)round(amount * 100);
    

    then work with cents instead. You can compare these to your heart's content.

    Thirdly, if the idea here is to work out change in quarters, dimes, nickels and pennies, a collection of if statements is not the way to go, unless you like long and inefficient programs. You will need to do that programatically. And that will be far easier if you have the integer number of cents above (hint: look at the % operator).

提交回复
热议问题