递归和斐波那契序列

如何使用此代码打印给定术语的斐波那契序列的所有值? 现在它只打印最后一个术语

#include  int fibonacci(int n){ if (n==2) return 1; else return fibonacci(n-1) + fibonacci(n-2); } int main() { int n; int answer; printf("Enter the number of terms you'd like in the sequence\n"); scanf("%d",&n); answer = fibonacci(n); printf("The answer is %d\n", answer); } 

你的基本情况不正确。 当n==2 ,你将调用fibonacci(1)fibonacci(0) 。 后者将继续向下,直到你的堆栈空间不足。

您应该检查小于等于基本情况的数字:

 if (n<=2) 

编辑:

如果要打印所有值,则由于双递归,您无法按照当前结构的方式执行此操作。

如果您跟踪之前计算过的数字,就可以完成。 然后,您只在第一次计算数字时打印出一个数字(并执行递归),否则您从列表中查找并继续。

 int fibonacci(int n){ static int seq[50] = {0}; if (n > 50) { printf("number too large\n"); return 0; } if (seq[n-1] == 0) { if (n<=2) { seq[n-1] = 1; } else { seq[n-1] = fibonacci(n-1) + fibonacci(n-2); } printf("%d ", seq[n-1]); } return seq[n-1]; } 

输出:

 Enter the number of terms you'd like in the sequence 10 1 1 2 3 5 8 13 21 34 55 The answer is 55 

请注意,上述函数的限制为50,因为对于该范围内的32位int,结果太大。