【发布时间】:2013-11-30 04:31:45
【问题描述】:
我最近开始学习 C#(已经学习过其他语言),我正在尝试创建一个函数,该函数使用 while 循环生成第 n 个术语的斐波那契数列,然后返回第 n 个值学期。 我目前的代码是这样的:
void fibonacci(int n)
{
int[] terms = { 0, 1 };
int i = 2;
while (i<=n)
{
terms.Concat( terms[i-1] + terms[i-2] );
i += 1;
}
return terms[n];
}
我对 C# 的理解很差,因为 Visual Studio 告诉我不能将“Concat”与 int[] 一起使用 - 我正在尝试将新值附加到数组中。任何帮助都会很棒。
【问题讨论】:
-
你的函数类型应该是 int[] : int[] fibonacci(int n)
-
@T-D - OP 想要返回传入的 index 处的值。返回类型应该是
int,而不是int[]。 -
@Oded 是的,你是对的,应该是
int,对不起。 -
这是您可以在 C# 中用于斐波那契计算的最佳方法:ilyatereschuk.blogspot.com/2013/12/blog-post.html
标签: c# loops while-loop sequence fibonacci