0

I don't know why theCount is returning 1 and not 2. It's like it doesn't think that the x and y are equal. I'm really stumped and need some help.

double num = 0.2;
list<double> myList = {};

for (int i = 0; i < 6; i++)
{
    num = num * 2;
    myList.push_back(num);

    if (num >= 1) {
        num = num - 1;
    }
}

cout << endl << "The List: ";
for (auto const j: myList) {
    cout << j << " ";
} cout << endl;

int theCount = 0;
cout << endl;
for (double x: myList) {
    for (double y: myList) {
        cout << x << " & " << y << ", ";
        if (x == y) {
            theCount++;
        }
    }
    cout << "-- theCount: " << theCount << endl;
    theCount = 0;
} cout << endl;

return 0;

Screenshot

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    Side note: Because `double`s are floating point numbers and floating point numbers are imprecise, comparing `double`s for equality can be problematic. For example in `if (x == y)` `x` could be 19.999999999999999999999999 and `y` could be 20.000000000000000000000001. Different enough to not be equal. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) for more information and a solution. – user4581301 Sep 08 '21 at 22:41
  • That is exactly the problem. And you can see this in action if you set `cout`'s precision higher than the default, say to 20 digits, eg then you will see the 1st `0.4` is really more like `0.40000000000000002220` whereas the 2nd `0.4` is really more like `0.40000000000000035527`, etc ([demo](https://ideone.com/f0pp3i)). So you need to compare the values against an epsilon and treat them as "equal" if they are "close enough" for your purposes. – Remy Lebeau Sep 08 '21 at 23:27

0 Answers0