float类型比较大小

转载自:秋叶原 && Mike || 麦克


float 型: 占 4 字节,7 位有效数字

double 型:占 8 字节,15~16 位有效数字


浮点数的表示是不精确的,float 和 double 都不能保证可以把所有实数都准确的保存在计算机中。测试例子如下:

[cpp]   view plain  copy
  1. #include <stdio.h>  
  2.   
  3. int main(int argc, char *argv[])  
  4. {  
  5.     float f = 99.9f;  
  6.     printf("f = %f\n", f);  
  7.       
  8.     return 0;  
  9. }  

运行结果如下:


扫描二维码关注公众号,回复: 3839535 查看本文章


由于浮点数的表示是不精确的,所以不能直接比较两个数是否完全相等。一般都是在允许的某个范围内认为某个个浮点数相等,如有两个浮点数a、b,允许的误差范围为 1e-6,则 abs(a-b) <= 1e-6,即可认为 a 和 b 相等。

[cpp]   view plain  copy
  1. #include <stdio.h>  
  2. #include <stdlib.h> //abs()  
  3.   
  4. int main(int argc, char *argv[])  
  5. {  
  6.     float a = 10.55f;  
  7.     float b = 10.55f;  
  8.       
  9.     if( abs(a-b) <= 1e-6 ){  
  10.         printf("a 等于 b\n");  
  11.     }else{  
  12.         printf("a 不等于 b\n");  
  13.     }  
  14.       
  15.     return 0;  
  16. }  

还有一种方法就是扩大再取整,比如 a=5.23、b=5.23,直接比较 a==b 有可能为 false,但是 a 和 b 都扩大一百倍,然后强制转换为 int 类型,再用 == 比较就可以了。

[cpp]   view plain  copy
  1. #include <stdio.h>  
  2.   
  3. int main(int argc, char *argv[])  
  4. {  
  5.     float a = 5.23;  
  6.     float b = 5.23;  
  7.       
  8.     if( (int)(a*100) == (int)(b*100) ){  
  9.         printf("a 等于 b\n");  
  10.     }else{  
  11.         printf("a 不等于 b\n");  
  12.     }  
  13.       
  14.     return 0;  
  15. }  

float 型变量和“零值”比较的方法:

[cpp]   view plain  copy
  1. #include <stdio.h>  
  2.   
  3. int main(int argc, char *argv[])  
  4. {  
  5.     float x = 0.000f;  
  6.     const float EPSINON = 0.000001;  
  7.     if (( x >= -EPSINON ) && ( x <= EPSINON ))  
  8.     {  
  9.         printf("x 是零\n");  
  10.     }  
  11.       
  12.     return 0;  
  13. }  

浮点型变量并不精确,其中 EPSINON 是允许的误差(即精度),所以尽量不要将 float 变量用 “==” 或 “!=” 与数字比较,应该设法转化成 “>=” 或 “<=” 形式。

猜你喜欢

转载自blog.csdn.net/IOT_Flower/article/details/78283086