Comparing currency values as floats does not work

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

提交回复
热议问题