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

C# 如何在C语言库中使用数组类型编写斐波那契序列?,c#,arrays,fibonacci,C#,Arrays,Fibonacci,我正在写一个图书馆,里面有几种常用的数学方法,以此来磨练我的技能。我正在尝试使用数组实现斐波那契序列。以下是库中的代码: public static int[] Fibonacci(int numElement) { int n = numElement - 1; int[] a = new int[numElement + 1]; a[0] = 0; a[1] = 1; for (int

我正在写一个图书馆,里面有几种常用的数学方法,以此来磨练我的技能。我正在尝试使用数组实现斐波那契序列。以下是库中的代码:

     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;

    }
}
但是,这是上述代码9的输出,用于输入:

0

一,

一,

0

0

0

0

0

0

以相同输出格式的任何其他输入结果。如何修复代码以获得所需的输出


编辑:不管返回语句的位置或它的存在,循环似乎都不会迭代。

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

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语句位于错误的位置,并且返回了循环中当前的错误类型元素,而不是数组。如果将方法更改为以下内容,则还将生成一些不必要的变量,这应该可以正常工作

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;
}

你也可以在这里查看一把正在使用的小提琴:

你过早地返回,并且输入了错误的类型-正如@konked所指出的。然而,他提供的解决方案仍然存在一个问题:Fibonacci9应该等于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;
}

您将在循环中返回,因此在第一次迭代之后,将只接触前三个元素。使用断点并使用调试器跟踪程序流。@P.basimfar只需在Fibonacci函数中从For循环中删除返回行,它就可以正常工作。使用调试器逐步检查代码,看看有什么问题。@BalrajSingh删除return语句也不起作用。同样的输出我编辑了代码,以显示即使返回语句不在for循环中,我也无法得到正确的答案。如果您注意到答案不一致,这就是原因。感谢您的回答,但是代码仍然不起作用。输出与以前相同。输出与以前相同。我更改了代码。根据我前面代码的调试器,循环根本不会迭代。可能是引用有问题。因为我正在另一个项目中使用该方法,我在其中添加了我的库。。。有什么想法吗?
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;
}