首先看geeksforgeeks上的两个程序:
程序1:
#include<stdio.h>
int main()
{
float x = 0.1;
if (x == 0.1)
printf("IF");
else if (x == 0.1f)
printf("ELSE IF");
else
printf("ELSE");
}
程序2:
#include<stdio.h>
int main()
{
float x = 0.5;
if (x == 0.5)
printf("IF");
else if (x == 0.5f)
printf("ELSE IF");
else
printf("ELSE");
system("pause");
return 0;
}
程序1输出是:ELSE IF, 而程序2,输出是:IF
为什么呢?
这是因为double和float的精度不一样,如果小数转换为二进制的时候是无限循环的话,那么就会出现对比值不一样,比如0.1,否则就可以比较float和double,结果值相等,比如0.5.
这就需要应用到小数转换为二进制的知识了,所谓的乘2取整法。
如0.1转换为二进制为:
0.1 * 2 = 0.2 ---- 整数为0,故取该位为0
0.2*2 = 0.4 -----整数为0,继续取0
0.4*2 = 0.8 -----整数为零,取零
0.8*2 = 1.6-----整数为1,取1
0.6*2 = 1.2----取1
0.2*2 = 0.4---取零,和前面循环了。
故此0.1(base 10) == 0.00011 0011 0011...(0011为无限循环数位值)
这样的数取不同精度,那么肯定会导致其值不一样的了。
故此:(float)0.1 != double(0.1)
但是0.5(base 10) = 0.1(base 2),没有无限循环数位
故此:(float)0.5 == double(0.5)
参考:http://www.geeksforgeeks.org/comparison-float-value-c/