浮点比较 `a != 0.7` [英] Floating point comparison `a != 0.7`
问题描述
可能重复:
浮点比较中的问题
#include <stdio.h>
#include <conio.h>
main()
{
float a = 0.7;
if(a < 0.7)
printf("C");
else
printf("C++");
}
在上面的代码中,输出是C
.我在 Code::Blocks 和 Pelles C 中尝试了这段代码,但得到了相同的答案.我想详细了解一下原因!
In the above code, the output is C
. I tried this code in Code::Blocks and Pelles C but got the same answer. I would like know the reason for this in detail!
推荐答案
在二进制中,0.7 是:
In binary, 0.7 is:
b0.1011001100110011001100110011001100110011001100110011001100110...
但是,0.7
是一个双精度字面量,其值是 0.7 舍入到最接近的可表示双精度值,即:
However, 0.7
is a double-precision literal, whose value is 0.7 rounded to the closest representable double-precision value, which is:
b0.10110011001100110011001100110011001100110011001100110
十进制,就是这样:
0.6999999999999999555910790149937383830547332763671875
当您编写 float a = 0.7
时,该双精度值再次四舍五入为单精度,而 a
获取二进制值:
When you write float a = 0.7
, that double value is rounded again to single-precision, and a
gets the binary value:
b0.101100110011001100110011
正是
0.699999988079071044921875
十进制.
当你进行比较 (a < 0.7)
时,你是在比较这个单精度值(转换为双精度,它不会四舍五入,因为所有单精度值都可以用双精度表示精度)到原来的双精度值.因为
When you do the comparison (a < 0.7)
, you are comparing this single-precision value (converted to double, which does not round, because all single-precision values are representable in double precision) to the original double-precision value. Because
0.699999988079071044921875 < 0.6999999999999999555910790149937383830547332763671875
比较正确返回 true,并且您的程序打印 "C"
.
the comparison correctly returns true, and your program prints "C"
.
请注意,这在 C++ 中没有任何不同,所讨论的代码的外观恰恰相反.有某些(数值上不安全的)编译器优化可以改变行为,但这些并不是 C 或 C++ 独有的.
Please note that none of this is any different in C++, appearances of the code in question to the contrary. There are certain (numerically unsafe) compiler optimizations that can change the behavior, but those are not unique to C or C++.
这篇关于浮点比较 `a != 0.7`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!