0

I have a problem with simple while loop. This code cout 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8 and it ends on number 1.9 and doesn't go futher to 2. My code:

float start = 1, end = 2, delta = 0.1;

while (start <= end)
{
    cout << start << endl;
    start += delta;
}

In debug I see that the last number is 1.90000021. And other also has many zeros after comma. If I change type to double, I have the same error. Please, if you know, say me how to fix it? I need to destinate start=2 in while-loop.

enter image description here

Nika
  • 379
  • 2
  • 16
  • 2
    using floating point numbers for loop counters / conditions is often a bug. If you want 10 iterations then you can use `int i` and `double x = 0.1 * i` for the value inside the loop – 463035818_is_not_an_ai May 04 '22 at 09:13
  • Can you set `end` to `2.05`? So the end value plus half the delta. – mch May 04 '22 at 09:13
  • Thanks for your answer. But I can't to set 2.05, because in my program I'll get those numbers from console. And I don't know how many iterations it'll be.. – Nika May 04 '22 at 09:17
  • You can use half the delta: `while (start <= end + delta/2)`. This is not perfect, and will often fail for corner cases like `start=0.0, end=10.5, delta=1.0`, but it's the best we can do with floating point. The issue is that floating point ranges are inherently sensitive to rounding errors. – chi May 04 '22 at 13:01

0 Answers0