加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – BigInteger不能代表无穷大

发布时间:2020-12-15 23:46:34 所属栏目:百科 来源:网络整理
导读:当我运行此代码时,我得到运行时异常 OverflowException: BigInteger cannot represent infinity. BigInteger sum=0;for (double i=1 ; i=1000 ;i++ ) sum += (BigInteger) Math.Pow(i,i);Console.WriteLine(sum); 根据我的理解,BigInteger值应该没有限制.那
当我运行此代码时,我得到运行时异常

OverflowException: BigInteger cannot represent infinity.

BigInteger sum=0;
for (double i=1 ; i<=1000 ;i++ )
    sum += (BigInteger) Math.Pow(i,i);
Console.WriteLine(sum);

根据我的理解,BigInteger值应该没有限制.那么为什么它会抛出OverflowException呢?

解决方法

这是因为你超过了双倍的限制.

Math.Pow有双精度计算,所以有限结果只能大约1.7e308,你超过i = 144的数字.所以它导致double.PositiveInfinity,无法转换为BigInteger. BigInteger对于无穷大没有特殊的表示方式,它只能存储整数,无穷大不是整数 – 即使BigInteger没有限制,它也永远不会达到无穷大. BigInteger实际上也有一个限制,当它用于存储数字的内部数组达到其最大大小时(可能会更快地耗尽内存).

在这种情况下,您可以使用BigInteger.Pow来避免这种情况,例如

BigInteger sum = 0;
for (int i = 1; i <= 1000; i++)
    sum += BigInteger.Pow(i,i);

正如预期的那样,结果非常大.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读