문제

I have two doubles, a and b, in C++ that should be equal but for some reason are not being treated as such. The following code:

cout << a << "==" << b << ": " << (a == b) << endl;

is outputting

0.5 == 0.5: 0

Any ideas why this is resolving to false?

도움이 되었습니까?

해결책

To avoid errors when comparing decimals it might be useful to use a function:

bool AreSame(double a, double b)
{
    return fabs(a - b) < EPSILON;
}

where EPSILON could be represented by a small number such as .001

grabbed from this question.

EDIT: by including <limits> one could use std::numeric_limits<double>::epsilon()

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top