【发布时间】:2017-11-01 13:38:08
【问题描述】:
我正在尝试为小于 100 万的数字创建斐波那契数列,然后找到数列中每个偶数的总和。
为此,我尝试使用斐波那契数列创建一个列表,然后使用带有 mod 的 for 循环来查找偶数 (n % 2 = 0),然后添加它们,但是在尝试创建斐波那契数列时我遇到了这个错误:
System.ArgumentOutOfRangeException。
这是我的代码:
{
class Program
{
static void Main(string[] args)
{
// creates a list with the fib[0]= 0 and fib[1] = 1
List<int> fib = new List<int>(new int [] {0, 1});
/// for loop that creates the next element in the fib sequence list by creating the next element by adding the previous two elements.
for (int i = 2; i < 100; i++)
{
fib[i] = (fib[(i - 1)] + fib[(i - 2)]);
}
Console.WriteLine(fib);
Console.ReadLine();
}
}
}
这没有出现构建错误,所以我无法解决问题。我认为 i - 2 可能会导致负数,这就是问题所在,也是 c# 所建议的,但我认为情况并非如此。
【问题讨论】:
-
你必须使用
fib.Add而不是索引器fib[i],即fib.Add(fib[(i - 1)] + fib[(i - 2)])。