Explain this floating point behavior

前端 未结 6 2184
野的像风
野的像风 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:45

    Floating point numbers are not exact. Specifically, your number is not necessarily compared against a float. The same code works as you expect if you use '0.7f' instead of '0.7' (on at least my compiler), but you should generally be comparing against a threshold, as the previous answer states.

提交回复
热议问题