SoulReaper1680 -4 Newbie Poster

Hey, when I run the following code:

for(double i = 3; i >= 0; i -= 0.2)
{
      cout << i << " ";
}

I get the output "3 2.8 2.6 2.4 2.2 2 1.8 1.6 1.4 1.2 1 0.8 0.6 0.4 0.2". For some reason, it doesn't output 0 at the end.

To test this, I changed the increment section of the for loop to i -= 0.25 instead and it displayed the following: "3 2.75 2.5 2.25 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0".

This time it displayed the 0 at the end as expected but, I don't understand why it doesn't display 0 for i -= 0.2.

Thank you :)

Edit:
I realised why this is happening. Floats and doubles aren't accurate enough to be used as counters.

The following code works perfectly:

for(int i = 30; i >= 0; i -= 2)
{
      cout << double(i) / 10.0 << " ";
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.