双重数学和布尔检查给出错误的答案

问题描述 投票:-1回答:2

使用此c ++代码:

double d = 0.3028 + 0.0028;
cout << d << endl;
if (d == 0.3056)
    cout << "match" << endl;
else
    cout << "not a match" << endl;

为什么输出“不匹配”?

c++ double
2个回答
0
投票

这是有限精度数学的性质。

如果使用例如十进制精度的六位数字,则1/3将表示为0.333333,如果您使用“ 3 * 1/3”,则将得到0.999999,而不是1。

类似地,2/3为0.666667,所以2 * 1/3将不等于2/3。 1/3 + 1/3将得到0.666666,而不是2/3。

有限精度表示很有趣,因此测试它们的精确相等性通常是一个坏主意。


0
投票

这是因为浮点数如何存储在内存中。这是一篇很好的文章:https://dev.to/visheshpatel/how-floating-point-no-is-stored-memory-47od

相反,如果“几乎相等”,则应检查浮点数(和双精度数)。在您的情况下,如果您只对小数点后四位感兴趣,则可以检查差异是否小于0.00001。因此:

float epsilon = 0.00001;

double a = d; //your value
double b = 0.3056; //the value to which you are comparing

bool equal_ab = abs(a - b) < epsilon;
© www.soinside.com 2019 - 2024. All rights reserved.