Like everyone else, this is done so that real numbers are infinite and uncountable, while floating point representations use a finite number of bits. Floating-point numbers can approximate real numbers and even in many simple cases are not exact due to their definition. As you now notice, 0.2 is actually not 0.2 , but rather a number very close to it. When you add them to value , you accumulate an error at every step.
Alternatively, try using int for your iteration and split the result to return it to the desired domain:
for (int value = -20; value <= 20; value += 2) { std::cout << (value / 10.f) << std::endl; }
For me it gives:
-2 -1.8 -1.6 -1.4 -1.2 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
source share