gpt4 book ai didi

c# - 仅使用正整数时返回负值

转载 作者:太空宇宙 更新时间:2023-11-03 17:09:45 26 4
gpt4 key购买 nike

运行以下代码时,我最终得到负值。我只使用正数,所以我真的很困惑。我试图查看这个负数是否是返回码,但似乎没有任何代码将其作为数字返回。

  public static int fib(int n)
{
int a = 0;
int b = 1;
for (int i = 0; i < n; i++)
{
int temp = a;
a = b;
b = temp + b;
}

return b;
}

static void Main(string[] args)
{
int n = 0;
bool Run = true;

while (Run == true)
{
n = fib(n + 1);
Console.WriteLine(n);
}
}

代码运行结果如下:

1
2
3
5
13
610
-121099088
1

最佳答案

您刚刚看到整数溢出。您正在尝试计算 fib(610),这远远超过 Int32 可以容纳的值 - 当您将两个大整数相加时,您将得到一个负数.

如果您以“已检查”模式构建它,则会抛出一个异常 - 或者您可以只为您需要的一个表达式执行此操作:

for (int i = 0; i < n; i++)
{
int temp = a;
a = b;
b = checked(temp + b);
}

有关 checked arithmetic 的更多信息,请参阅 MSDN .

关于c# - 仅使用正整数时返回负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8388218/

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