无限循环与浮动 [英] Endless for loop with float

查看:139
本文介绍了无限循环与浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码:

  for(float i = 0f; i  {
//一些代码
}

0 int.MaxValue (2 31 -1),但它不会'吨。一旦 i 达到2 24 i ++ 我完全无法理解。

在VS的即时窗口中,我试过这个:

 > i 
16777216.0
> i + 1
16777216.0 // ???
> i == i + 1
false //如预期的那样,但是与上面的语句不一致
> i + 2
16777218.0

为什么它的行为如此呢?什么是特殊的2 24 +1?

解决方案

这是因为float精度。它基于IEEE浮点运算标准( IEEE 754 )。阅读它来理解浮点是如何工作的。

简单地说,当一个float存储一个大的值时,当前存储的数字和它可以存储的下一个数字之间的差异大于1,因此加1不会增加它的值。

如果您需要精确的十进制数使用十进制代替。

如果您需要整数值比int大,然后使用 long

如果您需要非常大的整数值,请使用 BigInteger


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?

解决方案

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.

这篇关于无限循环与浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆