无法正确打印递归斐波那契数列
Unable to print recursive fibonacci sequence correctly
我正在尝试编写一个递归的 Fibonacci 生成器,它在 C 中打印每个项。项的数量是用户指定的;我已经开发了算法。当我尝试打印时,它只会打印一些。谁能指出我哪里出错了?
#include <stdio.h>
#include <stdlib.h>
int Fibonacci (int n)
{
if (n = 0)
return 0;
if (n = 1)
return 1;
else
return (Fibonacci(n-1) + Fibonacci(n-2));
}
int main()
{
int terms;
printf("Enter the number of terms: ");
scanf("%d", &terms);
printf("\nThe Fibonacci sequence containing %d terms is:\n", terms);
int i = 0;
for (i; i < terms; i++)
{
printf("%d ", Fibonacci(i));
}
return 0;
}
if (n == 0)
没有
if (n=0)
仔细检查你的语法。
您使用了一个等号,因此您分配了一个值而不是进行比较
if (n == 0)
return 0;
if (n == 1)
return 1;
...
你可以试试这个逻辑:
int Fibonacci (int n)
{
if(n < 2)
return n;
else
return Fibonacci(n- 1) + Fibonacci(n- 2);
}
这里n<2
表示递归将在项数为< 2
时终止,因为我们知道斐波那契数列的前两项是0
和1
。
我正在尝试编写一个递归的 Fibonacci 生成器,它在 C 中打印每个项。项的数量是用户指定的;我已经开发了算法。当我尝试打印时,它只会打印一些。谁能指出我哪里出错了?
#include <stdio.h>
#include <stdlib.h>
int Fibonacci (int n)
{
if (n = 0)
return 0;
if (n = 1)
return 1;
else
return (Fibonacci(n-1) + Fibonacci(n-2));
}
int main()
{
int terms;
printf("Enter the number of terms: ");
scanf("%d", &terms);
printf("\nThe Fibonacci sequence containing %d terms is:\n", terms);
int i = 0;
for (i; i < terms; i++)
{
printf("%d ", Fibonacci(i));
}
return 0;
}
if (n == 0)
没有
if (n=0)
仔细检查你的语法。
您使用了一个等号,因此您分配了一个值而不是进行比较
if (n == 0)
return 0;
if (n == 1)
return 1;
...
你可以试试这个逻辑:
int Fibonacci (int n)
{
if(n < 2)
return n;
else
return Fibonacci(n- 1) + Fibonacci(n- 2);
}
这里n<2
表示递归将在项数为< 2
时终止,因为我们知道斐波那契数列的前两项是0
和1
。