比较浮点数和双精度数 [英] Comparing float and double
本文介绍了比较浮点数和双精度数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <stdio.h>
int main(void){
float a = 1.1;
double b = 1.1;
if(a == b){
printf("if block");
}
else{
printf("else block");
}
return 0;
}
打印:否则阻止
#include <stdio.h>
int main(void){
float a = 1.5;
double b = 1.5;
if(a == b){
printf("if block");
}
else{
printf("else block");
}
return 0;
}
打印:如果阻塞
这背后的逻辑是什么?
使用的编译器:gcc-4.3.4
Compiler used: gcc-4.3.4
推荐答案
这是因为 1.1
不能完全用二进制浮点表示.但是 1.5
是.
This is because 1.1
is not exactly representable in binary floating-point. But 1.5
is.
因此,float
和 double
表示将持有稍有不同的 1.1
值.
As a result, the float
and double
representations will hold slightly different values of 1.1
.
这正是写成二进制浮点数时的区别:
Here is exactly the difference when written out as binary floating-point:
(float) 1.1 = (0.00011001100110011001101)₂
(double)1.1 = (0.0001100110011001100110011001100110011001100110011010)₂
因此,当您比较它们时(并且 float
版本得到提升),它们将不相等.
Thus, when you compare them (and the float
version gets promoted), they will not be equal.
这篇关于比较浮点数和双精度数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文