I found a bug in my program with some specific values. The conversion to int
is wrong. The results should be 201 but the results is 200. Why it is wrong and how to safely convert to int
?
#include <iostream>
using namespace std;
int main()
{
double y = 591860.6;
double x = 591820.4;
double r = 0.2;
cout << (y - x) / r << " " << (int)((y - x) / r) << endl;
return 0;
}
201 200
I found a workaround but yet I don't understand why it works
(int)(float)((y - x) / r)
201 201