float a = 0;
while (true)
{
a++;
if (a > 16777216)
break; // Will never break... a stops at 16777216
}
谁能向我解释为什么在这段代码中浮点值在 16777216 处停止递增?
Can anyone explain this to me why a float value stops incrementing at 16777216 in this code?
或者更简单:
float a = 16777217; // a becomes 16777216
对 IEEE-754 浮点数(32 位)的简短总结:
Short roundup of IEEE-754 floating point numbers (32-bit) off the top of my head:
(sign ? -1 : +1) * 2^exponent * (1.0 + mantissa)
1001 0000 0000 0000 0000 000 = 2^-1 + 2^-4 = .5 + .0625 = .5625
不存储小数点分隔符前面的值,而是隐式假定为 1 (如果指数为 255,则假定为 0,但这在这里并不重要),因此对于 30 的指数,例如,这个尾数示例表示值 1.5625
(sign ? -1 : +1) * 2^exponent * (1.0 + mantissa)
1001 0000 0000 0000 0000 000 = 2^-1 + 2^-4 = .5 + .0625 = .5625
and the value in front of the decimal separator is not stored but implicitly assumed as 1 (if exponent is 255, 0 is assumed but that's not important here), so for an exponent of 30, for instance, this mantissa example represents the value 1.5625
现在来看你的例子:
16777216 正好是 224,并且会像这样表示为 32 位浮点数:
16777216 is exactly 224, and would be represented as 32-bit float like so:
10010111
)0 10010111 00000000000000000000000
(+1) * 2^24 * (1.0 + .0) = 2^24 = 16777216
现在让我们看看数字 16777217,或者正好是 224+1:
Now let's look at the number 16777217, or exactly 224+1:
(+1) * 2^24 * (1.0 + 2^-24) = 2^24 + 1 = 16777217代码>
(+1) * 2^24 * (1.0 + 2^-24) = 2^24 + 1 = 16777217
这篇关于为什么浮点变量在 C# 中在 16777216 处停止递增?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!