0

Below you can find a basic C++ exercise with a for loop, the question is: what is the value of i after the loop runs. (Apparently, the value is 5.)

My question, on the 5th run (i=5), the value of a is 100, shouldn't the loop stop since the condition is a<100? Isn't the condition checked after a is multiplied with 10? (so after a is already 100)

If I check the value of a after the loop exit, it will be 1000. I am confused. Why does the loop not stop at 100?

#include <iostream>
using namespace std;
int main(void) {
    float a;
    int i = 0;
    for(a = 0.01; a < 1e2; a *= 1e1)
        ++i;

    return 0;
}
Laur
  • 74
  • 7

2 Answers2

7

The exercise is designed to show that float (and double etc., floating point numbers in general) do not have the exact decimal value as what you see in the program text.

0.01 (decimal) cannot be exactly represented in the binary floating point format used, therefore multiplying 10 five times will not yield exactly 100.0.

See also: Floating point inaccuracy examples

palotasb
  • 4,108
  • 3
  • 24
  • 32
2

You can't tell exactly what will happen with this code without knowing the details of the floating point implementation on your platform; the C++ standard leaves this intentionally flexible.

In essence 0.01 could be an approximation for the closest float to that double literal. So the stopping conditional a < 1e2 could be met prematurely or otherwise.

Note that along with 0.01, 1e1 is a literal of type double.

So the conversions to float are complicating things further. Then there is floating point strictness to consider.

Cut a long story short: don't use a floating point as the "index" in a loop.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483