考虑以下代码:
for (float i = 0f; i < int.MaxValue; i++)
{
// Some code
}
Which is supposed to loop from 0
to int.MaxValue
(231-1), but it doesn't. Once i
reached 224, i++
doesn't work anymore for a reason that I'm totally unable to understand.
在 VS 的立即窗口中我尝试过以下操作:
>i
16777216.0
>i + 1
16777216.0 // ???
>i == i + 1
false // as expected, but a lack of consistency with upper statement
>i + 2
16777218.0
Why does it behave like so? What is special with 224+1?
这是因为浮动精度。它基于 IEEE 浮点运算标准 (IEEE 754)。阅读它以了解浮点的工作原理。
简单来说,当浮点数本身存储一个大值时;当前存储的数字与它可以存储的下一个数字之间的差值大于 1,因此加 1 不会增加其值。
如果您需要精确的十进制数,请使用decimal反而。
如果您需要大于 int 的整数值,则使用long.
如果您需要非常大的整数值,那么使用大整数.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)