比较浮点型和双精度型
#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;
}
打印:else block
#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;
}
打印:if block
这背后的逻辑是什么?
使用的编译器:gcc-4.3.4
#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;
}
Prints: else block
#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;
}
Prints: if block
What is the logic behind this?
Compiler used: gcc-4.3.4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为
1.1
不能完全用二进制浮点表示。但1.5
是。因此,
float
和double
表示形式将保存稍微不同的1.1
值。这正是写为二进制浮点时的区别:
因此,当您比较它们时(并且
float
版本得到提升),它们将不相等。This is because
1.1
is not exactly representable in binary floating-point. But1.5
is.As a result, the
float
anddouble
representations will hold slightly different values of1.1
.Here is exactly the difference when written out as binary floating-point:
Thus, when you compare them (and the
float
version gets promoted), they will not be equal.必读:每个计算机科学家应该了解的浮点运算< /a>
Must read: What Every Computer Scientist Should Know About Floating-Point Arithmetic
二进制 1.1 十进制的精确值是非结尾分数 1.00011001100110011001100(1100).... 双常量
1.1
是尾数的 53 位截断/近似值。现在,当转换为浮点数时,尾数将仅以 24 位表示。当
float
转换回 double 时,尾数现在又回到 53 位,但超过 24 位的所有内存都将丢失 - 该值被零扩展,现在您正在比较 (例如,取决于舍入行为)并且
现在,如果您使用 1.5 而不是 1.1;
十进制 1.5 恰好是二进制的 1.1。它可以精确地用2位尾数表示,因此即使是24位浮点数也是夸张的......你所拥有的是
和
后者,零扩展到双精度将是
这显然是相同的号码。
The exact value of 1.1 decimal in binary is non-ending fraction 1.00011001100110011001100(1100).... The double constant
1.1
is 53-bit truncation / approximate value of that mantissa. Now this when converted to float, the mantissa will be represented just in 24 bits.When the
float
is converted back to double, the mantissa is now back to 53 bits, but all memory of the digits beyond 24 are lost - the value is zero-extended, and now you're comparing (for example, depending on the rounding behaviour)and
Now, if you used 1.5 instead of 1.1;
1.5 decimal is exactly 1.1 in binary. It can be presented exactly in just 2 bit mantissa, therefore even the 24 bits of float are an exaggeration... what you have is
and
The latter, zero extended to a double would be
which clearly is the same number.