Please read What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Floating point types can not represent every possible numeric value. They have some imprecision. The closest representable IEEE754 single-precision floating point value to 0.84
is 0.839999973773956298828125
. This is a little less than 0.84
. As you have seen, when printed, this is shown as as 0.839999
. The binary representation of this number is:
00111111 01010111 00001010 00111101
In fact, even 0.01
is not exactly representable with float
, so every time you add this value to x
, your expectation becomes less and less precise. You can avoid this by using int
s instead, like so:
for (int x = 0; x < 100; x += 1) {
cout << (x / 100.0f) << endl;
}
However, many of the values it prints will still not be representable after performing the division. If you can't deal with imprecision at all, you must simply not work with floating point values. Store your values as int
s and simply interpret them as representing the corresponding divided by 100 float
value.