Explain this floating point behavior

前端 未结 6 2193
野的像风
野的像风 2020-12-21 18:30

Please explain why the following pieces of code behave differently.

#include
int main(){
 float a=0.1;
 if(a<0.1)
  printf(\"less\");
 else         


        
6条回答
  •  清歌不尽
    2020-12-21 18:52

    #include
    
    int main() {
        float a = 0.7;
        if (a < 0.7)
            printf("less");
        else 
            printf("greater than equal");
        getchar();
    }
    

    Unsuffixed floating constants are of type double not float. For example, 0.7 is a floating constant of type double.

    if (a < 0.7)
    

    As the right operand in the comparison expression is of type double, the usual arithmetic conversion apply and the a value is promoted to double. double and float don't have the same precision. In your case to get the correct result you should have used a floating constant of type float.

    if (a < 0.7f)
    

    0.7f is a floating constant of type float.

提交回复
热议问题