递归和斐波那契数列

Recursion and fibonacci sequence

如何让这段代码打印给定项的斐波那契数列的所有值?现在它只打印最后一项

#include <stdio.h>

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)。后者将继续向下,直到你 运行 出栈 space.

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

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,结果太大了。