我試圖在總結一些數字的循環,但如我所料將這些數字在for循環中
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");
這個程序打印也沒有去:
0.1 + 0.1 = 0.200000
總和必須設爲100000
真正的總和:
100958.343750
按任意鍵繼續。 。 。
你能解釋一下這個奇怪的結果嗎?
不要擔心:幾乎每個開發者都會陷入這個陷阱。您確實需要了解[浮點數](https://en.wikipedia.org/wiki/Floating_point)在計算機中的工作方式。重要的部分是浮點數不能_exactly_表示大多數數字,你總會有錯誤。就你而言,小錯誤加起來直到它們變大。 – DarkDust
非常感謝你真的幫了我 –