Endless for loop with float

早过忘川 提交于 2019-12-20 02:34:39

问题


Consider the following code:

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.

In the Immediate Window of VS I've try this:

>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?


回答1:


It is because of float precision. It is based on IEEE Standard for Floating-Point Arithmetic (IEEE 754). Read it to understand how floating point works.

In simple words when a float stores a large value in itself; the difference between currently stored number and the next number it can store, is larger than 1 so adding 1 to it does not increase it's value.

If you need exact decimal number use decimal instead.
If you need integral value larger than int then use long.
If you need very large integral values then use BigInteger.



来源:https://stackoverflow.com/questions/36444413/endless-for-loop-with-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!