0

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

JRR
  • 3,024
  • 2
  • 13
  • 37
  • 3
    Your first `201` is not really 201. It's `200.9999999997672` and `cout` rounds it. Use `std::setprecision(16)` when debuging using `cout`, or use your debugger to see the real value. – NathanOliver Aug 05 '19 at 17:44
  • Well actually I understand the problem and I know it comes from floating point precision. But how can I get an integer in this case? With `round`? – JRR Aug 05 '19 at 17:47
  • 2
    `round` seems like a good choice – john Aug 05 '19 at 17:48
  • Using `(int)` as cast does not round, it just throws everything away after the decimal point [C++: How to round a double to an int?](https://stackoverflow.com/questions/9695329/c-how-to-round-a-double-to-an-int) – t.niese Aug 05 '19 at 17:48
  • 1
    `round` sounds like what you want. There is also `floor` and `ceil` but you'd need to know which one to use which round does for you. You just have to decide if you'd rather have rounding or truncation as that is a big difference. – NathanOliver Aug 05 '19 at 17:50
  • Will use `round` thanks. – JRR Aug 05 '19 at 17:51
  • You should calculate `(y - x)` once and store into a temporary `const` variable. – Thomas Matthews Aug 05 '19 at 18:50
  • std::cout << "rounded value = " << std::round((y - x) / r) << '\n'; – kato2 Aug 05 '19 at 20:19

0 Answers0