【问题标题】:System.ArgumentOutOfRangeException: when creating a fibonnaci sequence [duplicate]System.ArgumentOutOfRangeException:创建斐波那契数列时[重复]
【发布时间】: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)])

标签: c# fibonacci


【解决方案1】:

您的列表中只有 2 个元素,在 i=2 迭代中,它会抛出 ArgumentOutOfRangeException 异常。

【讨论】:

  • 即使我执行 i= 3 它仍然无法工作,但它应该可以使用 i = 2 不应该,因为 2-2 是 0 并且第 0 个元素是列表中的第一个元素?
猜你喜欢
  • 2023-03-09
  • 2013-10-04
  • 1970-01-01
  • 2015-06-05
  • 2021-10-17
  • 2011-05-06
相关资源
最近更新 更多