如何在 C# 库中使用数组类型编写斐波那契数列?

How to write the Fibonacci sequence using array type inside a library in C#?

我正在编写一个包含几种常用数学方法的库,以此来磨练我的技能。我正在尝试使用数组实现斐波那契数列。这是库中的代码:

     public static int[] Fibonacci(int numElement)
     {
        int n = numElement - 1;
        int[] a = new int[numElement + 1];
        a[0] = 0;
        a[1] = 1;



        for (int i = 2; i <= n; i++)
        {
            a[i] = a[i - 2] + a[i - 1];

        }

      return a;

    }
}

为了测试它,我使用了一个控制台应用程序,我在其中引用了我的 dll:

    static void Main(string[] args)
    {
        int[] b = new int[9];
        b = numberTheory.Fibonacci(9);
        foreach (var item in b)
        {
            Console.WriteLine(item);
        }
    }
}

然而,这是上面代码的输出(9为输入):

0

1

1

0

0

0

0

0

0

任何其他输入都会产生相同的输出 格式。如何修复我的代码以获得所需的输出?

EDIT :无论 return 语句的位置如何(或其存在),循环似乎都不会迭代。

序列的生成过早终止。修改如下。

public static int[] Fibonacci(int numElement)
{
    int n = numElement - 1;
    int[] a = new int[numElement + 1];
    a[0] = 0;
    a[1] = 1;
    for (int i = 2; i <= n; i++)
    {
        a[i] = a[i - 2] + a[i - 1];
    }
    return a;
}

你的 return 语句在错误的地方并且 returning 错误的类型(当前在循环中的元素而不是数组),你也制作了一些不必要的变量如果您将方法更改为以下方法,它应该可以工作

public static int[] Fibonacci(int numElement)
{
    int[] a = new int[numElement];
    a[0] = 0;
    a[1] = 1;


    for (int i = 2; i < numElement; i++)
    {
        a[i] = a[i - 2] + a[i - 1];
    }

    return a;
}

您还可以在此处查看有效的 fiddle:https://dotnetfiddle.net/dWZck8

正如@konked 所指出的,您过早地返回了错误的类型。然而,他提供的解决方案仍然存在问题:Fibonacci(9) 应该等于 34(而不是 21)。所以你需要数组中的 n+1 个位置。

public int[] Fibonacci(int numElement)
{
     if (numElement < 0)
        throw new ArgumentOutOfRangeException("numElement", numElement, "Fibonnaci number to get must be greater or equal than 0");

        var n = numElement + 1; //you need n+1 positions. The 9th number is in 10th position
        var a = new int[n];
        a[0] = 0;

     if (numElement == 0)
         return a;

    a[1] = 1;

    for (var i = 2; i < n; i++)
        a[i] = a[i - 2] + a[i - 1];

    return a;
}