c++ fmod returns 0.2 for fmod(0.6,0.2)

后端 未结 3 615
执念已碎
执念已碎 2021-01-23 06:00

when I use fmod(0.6,0.2) in c++ it returns 0.2

I know this is caused by floating point accuracy but it seems I have to get remainder of two double this moment

th

3条回答
  •  情话喂你
    2021-01-23 06:19

    You're right, the problem is a rounding error. Try this code:

    #include 
    #include 
    int main()
    {
        double d6 = 0.6;
        double d2 = 0.2;
        double d = fmod (d6, d2);
        printf ("%30.20e %30.20e %30.20e\n", d6, d2, d);
    
    }
    

    When I run it in gcc 4.4.7 the output is:

    5.99999999999999977796e-01     2.00000000000000011102e-01     1.99999999999999955591e-01
    

    As for how to "fix" it, I don't know enough about exactly what you are trying to do to know what to suggest. There will always be numbers that cannot be exactly represented in floating point, so this kind of behavior is unavoidable.

    More information about the problem domain would be helpful to get better suggestions. For example, if the numbers you are working with always just have one digit after the decimal point, and are small enough, just multiply by 10, round to the nearest integer (or long or long long), and use the % operator rather than the fmod function. If you are trying to see whether the result of fmod is 0.0, simply accept a result that is close to 0.2 (in this case) as if it were close to 0.

提交回复
热议问题