You are likely experiencing floating point rounding issues, a very common problem that has been dealt with time and time again. Consider the following program:
float a, b, c;
cin >> a;
b = a;
a = a*3;
a = a/3;
c = a - b;
cout << c << " " << (c == 0) << endl;
By all rights you should get a print out of 0 1
, but when you try it here. You get:
2.48353e-09 0
This is because floating point numbers cannot represent every base 10 number, so rounding errors make straight comparisons a bad idea. You should always use an epsilon, ie:
abs(a - b) < eps
where eps
is something like 1e-6.
Here you can find many more examples.