这是昨天在MSDN Newsgroups上看到的,问题描述如下:
The following code:
float someFloat = 0;
for(int x = 1; x <= 10; x++)
{
someFloat += .1F;
Console.WriteLine(someFloat.ToString());
}
Returns:
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8000001
0.9000001
1
WHY, WHY, WHY, WHY, WHY, WHY, WHY, WHY, WHY, WHY, WHY!!! What happened to
the nice and rounded 0.8 and 0.9? I know that the float variable is prone to
rounding issues but come on!! I am just adding a 0.1. I haven't even gotten
to where it needs to start rounding!! What's going on???? Is this normal? It
probaly is, isn't it?
Rene遇到了这个问题,累加过程中出现了0.8000001的错误,四舍五入后肯定是错不了的,但是如果出现在需要准确计算的时候,这样的错误或许会留下隐患,what`s going on ? 看看作为MVP的Bruno Jouhier的回答:
The problem is that 0.1 cannot be represented **exactly** as a float
(surprise!)
Float (and double) can only represent exactly numbers that can be written as
m * 2^e where m and e are integers (possibly negative).
Numbers like 0.5, 0.25, 0.125 or 0.875 are exactly representable as floats
(1*2^-1, 1*2^-2, 1^2-3, 7*2^-3) but 0.1 is not (its binary representation is
infinite)!
So, 0.1f is only an approximation of 0.1 and the error will accumulate when
you add.
惊讶吧?0.1不能被正确的表现为float类型,只有能被写成m*2^e(m和e都是int型的,负数也可以)表示的才是真正意义上的浮点数,这样的数才不会造成我们使用时累加时出现error accumulate的情况。
然后我在试验了一下,的确是这样的,但是用VC6确没有这个错误。不死心,扩大一下范围,循环100次,每次加0.01,结果VC6在0.83开始出现了小错误,0.84成了0.8399999了。
记住哦,在使用浮点数的时候要小心了呀!