Explain this floating point behavior

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

    When you perform the comparison, you are comparing a float (with 24 bits of precision) with a double (with 53 bits of of precision). Your float value is created by rounding from the more precise double value. Sometimes it rounds down and sometimes it rounds. It will hardly ever be the same.

    Try your example again but test for all three possible results: equal, less, and greater.

    Try your example again with a as a double.

    Try your example again and compare against a float.

提交回复
热议问题