因为float和double类型的数据有数据精度,因此直接用“==”或者“!=”做比较会出现很多的问题,这类比较一般都使用宏定义一个数据精度,在精度允许误差范围内则认为两个数相等。
以最常见的问题做分析:
float a 与0作比较程序:
我们经常不这样写代码
if(a == 0.0)
{
printf("a equal 0");
}
而是这样写
#define EPSINON 1e-6
if(fabs(a-0.0) < EPSINON)
{
printf("a equal 0");
}
下面的代码将为我们解开疑惑:
1 #include <stdio.h>
2 #include <math.h>
3 #define EPSINON 1e-6
4
5 int main(int argc,char *argv[])
6 {
7 float a = 120.02;
8 float b = 120;
9 float c = 0.02;
10
11
12 if(a-b == c)
13 {
14 printf("%f - %f = %f\n",a,b,c);
15 }
16 printf("a = %f,b = %f,a-b = %f\n",a,b,a-b);
17
18
19 return 0;
20 }
执行结果如下:
[email protected]:~/c_language$ ./a.out
a = 120.019997,b = 120.000000,a-b = 0.019997
从以上代码就可以看出精度在float和double比较中的重要性