Floats being Inexact

前端 未结 2 660
别跟我提以往
别跟我提以往 2021-01-25 11:30

I am puzzled. I have no explanation to why this test passes when using the double data type but fails when using the float data type. Consider the foll

2条回答
  •  星月不相逢
    2021-01-25 11:47

    Try this:

    #include 
    
    int main(){
        float total = 0.00;
        int i;
        for (i = 0; i < 100; i++)
            total += 0.01;
    
        printf("%f\n", total);
    
        if (total == 1.0)
            puts("Precise");
        else
            puts("Rounded");
    }
    

    At least on most machines, you'll get an output of "Rounded". In other words, the result simply happens to be close enough that when it's printed out, it's rounded so it looks like exactly 1.00, but it really isn't. Change total to a double, and you'll still get the same.

提交回复
热议问题