Q:

adding numbers in a for loop

I tried to sum some numbers in a for loop but it didn't go as I expected
float sum = 0;
int i;

printf("0.1+0.1=%f\n", 0.1 + 0.1);

for (i = 0; i<1000000; i++)
{
    sum = sum + 0.1;

}
printf("the sum need to be 100000 \n");
printf("the real sum is:\n %f\n", sum);

system("PAUSE");

this program prints:
0.1+0.1=0.200000
the sum need to be 100000
the real sum is:
100958.343750
Press any key to continue . . .
can you explain please this strange result? 

A:

the international standard for floating point numbers does not have an exact representation for some decimal numbers.
http://en.wikipedia.org/wiki/IEEE_754
It is due to the way they are stored in memory, the way the mantissa and exponent are stored.
https://en.wikipedia.org/wiki/Floating_point
This is also the reason why you should never compare two float numbers even if they look "the same".
I still remember how surprised I was the fist time a simple code comparing two float numbers didn't work :) This alone would open a dedicated universe of discussions. It is very worth reading anyway:
http://floating-point-gui.de/errors/comparison/

