浮点比较 [英] Floating point comparison
问题描述
INT的main()
{
浮动= 0.7;
浮动B = 0.5;
如果(一个或下; 0.7)
{
如果(B小于0.5)的printf(2是右);
其他的printf(1是正确的);
}
其他的printf(0是对的);
}
我本来期望这code的输出为 0是正确
。
但令我失望的是输出为 1是正确
为什么?
INT的main()
{
浮动= 0.7,B = 0.5; //这些花车
如果(A< .7)//这是一个双
{
如果(B< .5)//这是一个双
的printf(2是正确的);
其他
的printf(1是正确的);
}
其他
的printf(0是对的);
}
花车获得比较期间晋升为双打,并且由于浮子precise增加了一倍少,0.7浮法是的不的相同的0.7为双。在这种情况下,当它被提升0.7浮法变差至0.7为双。正如Christian表示,0.5是2的权力始终用来重新presented准确,所以测试按预期工作: 0.5 LT; 0.5
是假的。
因此,无论
- 更改
浮动
到双击
或 - 更改
0.7
和.5,
到.7f
和.5f
,
,你会得到预期的行为。
int main()
{
float a = 0.7;
float b = 0.5;
if (a < 0.7)
{
if (b < 0.5) printf("2 are right");
else printf("1 is right");
}
else printf("0 are right");
}
I would have expected the output of this code to be 0 are right
.
But to my dismay the output is 1 is right
why?
int main()
{
float a = 0.7, b = 0.5; // These are FLOATS
if(a < .7) // This is a DOUBLE
{
if(b < .5) // This is a DOUBLE
printf("2 are right");
else
printf("1 is right");
}
else
printf("0 are right");
}
Floats get promoted to doubles during comparison, and since floats are less precise than doubles, 0.7 as float is not the same as 0.7 as double. In this case, 0.7 as float becomes inferior to 0.7 as double when it gets promoted. And as Christian said, 0.5 being a power of 2 is always represented exactly, so the test works as expected: 0.5 < 0.5
is false.
So either:
- Change
float
todouble
, or: - Change
.7
and.5
to.7f
and.5f
,
and you will get the expected behavior.
这篇关于浮点比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!