C#:无法在 For 循环中重新分配变量
C#: Cannot reassign variable within For loop
我正在编写一个程序来计算斐波那契数列中的特定值。递归的方法很完美,但是当我尝试使用 for 循环时,它的效果不是很好:
class Program
{
static int loopF(int n)
{
int result=0;
if (n == 1)
{
result = n;
}
else if (n == 2)
{
result = n;
}
else if (n>2)
{
int S1 = 1; int S2 = 2;
for (int i = 3; i>n; i++) {
result = S1 + S2;
S1 = S2;
S2 = result;
}
}
else{
Console.WriteLine("Input Error");
}
return (result);
}
static void Main()
{
Console.WriteLine(loopF(10)); //it gives me 0; wrong
Console.WriteLine(loopF(1)); //it gives me 1; correct.
}
}
有人知道我哪里错了吗?提前致谢。
你的循环退出条件是错误的。应该是
for (int i = 3; i < n ; i++) { ...
你的循环没有执行
for (int i = 3; i>n; i++)
变量 i 从 3 开始 - 在您的测试用例中 n = 10。
(10 < 3) = false 所以循环不执行。
尝试使用 less than
for (int i = 3; i < n; i++)
我正在编写一个程序来计算斐波那契数列中的特定值。递归的方法很完美,但是当我尝试使用 for 循环时,它的效果不是很好:
class Program
{
static int loopF(int n)
{
int result=0;
if (n == 1)
{
result = n;
}
else if (n == 2)
{
result = n;
}
else if (n>2)
{
int S1 = 1; int S2 = 2;
for (int i = 3; i>n; i++) {
result = S1 + S2;
S1 = S2;
S2 = result;
}
}
else{
Console.WriteLine("Input Error");
}
return (result);
}
static void Main()
{
Console.WriteLine(loopF(10)); //it gives me 0; wrong
Console.WriteLine(loopF(1)); //it gives me 1; correct.
}
}
有人知道我哪里错了吗?提前致谢。
你的循环退出条件是错误的。应该是
for (int i = 3; i < n ; i++) { ...
你的循环没有执行
for (int i = 3; i>n; i++)
变量 i 从 3 开始 - 在您的测试用例中 n = 10。 (10 < 3) = false 所以循环不执行。
尝试使用 less than
for (int i = 3; i < n; i++)