gpt4 book ai didi

c# - BigInteger 不能表示无穷大

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:04:11 24 4
gpt4 key购买 nike

当我运行这段代码时,我得到了运行时异常

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

最佳答案

发生这种情况是因为您超出了 double 的限制。

Math.Powdouble 中计算,因此有限结果只能与 1.7e308 一样大,您超过 i = 144 的数字。所以它导致 double.PositiveInfinity,无法转换为 BigIntegerBigInteger 没有像 double 那样对无穷大进行特殊表示,它只能存储整数而无穷大不是整数 - 即使 BigInteger 没有极限,它永远不会达到无穷大。 BigInteger 实际上也有一个限制,当它用来存储数字的内部数组达到其最大大小时(您可能会更快地耗尽内存)。

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

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

结果很大,符合预期。

关于c# - BigInteger 不能表示无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31754769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com