Comparing currency values as floats does not work

后端 未结 4 1236
忘了有多久
忘了有多久 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:22

    What is the most effective way for float and double comparison?

    You should use something like this

    bool isEqual(double a, double b)
    {
        return fabs(a - b) < EPSILON;
    }
    

    or this

    #define ISEQUAL(a,b) ( fabs((a) - (b)) < EPSILON)
    

    and define EPSILON

    #define EPSILON (0.000001)
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-12 05:27

    Declare your comparative value as a float.

    if (amount == 0.01f)
       printf("Quarters: 0\nDimes: 0\nNickels: 0\nPennies: 1");
    

    Note that you could encounter some undefined behavior by directly testing float equality if you made some calculations with your float variable.

    0 讨论(0)
  • 2020-12-12 05:30

    I think we could scale for a factor and make a relative comparison like this:

    #define EPSILON (0.000001)
    
    if (fabs(a - b) <= EPSILON * fmax(fabs(a), fabs(b))) {
    }
    

    which is more robust than an absolute comparison:

    if (fabs(a - b) <= EPSILON ) {
        // ...
    }
    

    which maybe scale dependent. By the way having the optimum scale depends also from the function, we shouldn't use the same formula for a log and for a sin.

    0 讨论(0)
提交回复
热议问题