简体   繁体   English

比较浮点数和常数时的奇怪行为

[英]Strange behavior when comparing float with a constant

I was struck by this strange behavior: 我被这种奇怪的行为所震惊:

float pi = 3.14;

if(pi == 3.14)
    cout << "OK";
else
    cout << "How is it possible?";

Could anyone explain this? 有人可以解释吗?

The constant in the if statement is (double)3.14 . if语句中的常量为(double)3.14 It is very close to its float version, but not exactly equals it, because 3.14 is not represented exactly. 它非常接近其float版本,但不完全相等,因为未精确表示3.14

Try the same trick with 1.25 or any other number that can be represented exactly, and you will get an OK . 1.25或可以精确表示的任何其他数字尝试相同的技巧,您将获得OK

float num = 1.25;
if(num == 1.25)
    cout << "OK";
else
    cout << "How is it possible?";

You could also cast 3.14 to float to get an OK : 您还可以将3.14 float以获得OK

float pi = 3.14;

if(pi == (float)3.14)
    cout << "OK";
else
    cout << "How is it possible?";

Because by default values like 3.14 are treated as double, but storing one of this value in a float variable causes a loss of precision; 因为默认情况下,像3.14这样的值被视为double值,但是将其中一个值存储在float变量中会导致精度损失; and so there are microscopic differences related to the different precisions. 因此存在与精度不同有关的微观差异。 Here's why floating point numbers shouldn't be compared directly most of the time. 这就是为什么大多数时候不应该直接比较浮点数的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM