Endless for loop with float

后端 未结 1 343
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 11:09

Consider the following code:

for (float i = 0f; i < int.MaxValue; i++)
{
    // Some code
}

Which is supposed to loop from 0 to

相关标签:
1条回答
  • 2021-01-21 11:39

    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.

    0 讨论(0)
提交回复
热议问题