【问题标题】:Unable to print recursive fibonacci sequence correctly无法正确打印递归斐波那契数列
【发布时间】:2016-10-31 14:27:56
【问题描述】:

我正在尝试编写一个递归斐波那契生成器,它在 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;
}

【问题讨论】:

  • 这对我来说似乎是家庭作业。我们不反对帮助人们完成家庭作业,只需将其标记为家庭作业,以便我们知道如何指导您。
  • @DanielRudy [homework] 标签不应该再使用了。
  • @Xufox 我不知道这一点。嗯,如果是作业的话,应该在帖子里提到。

标签: c recursion fibonacci


【解决方案1】:
if (n == 0)

不是

if (n=0)

仔细检查你的语法。

【讨论】:

    【解决方案2】:

    您使用单个等号,因此您分配了一个值而不是进行比较

    if (n == 0)
        return 0;
    if (n == 1)
        return 1;
    ...
    

    【讨论】:

    • if (0 == n) 更好。这样,如果你使用 = 而不是 == 它不会编译。
    【解决方案3】:

    你可以试试这个逻辑:

    int Fibonacci (int n)
    {
        if(n < 2)
           return n;
        else
           return Fibonacci(n- 1) + Fibonacci(n- 2);
    }
    

    这里的n&lt;2 表示当项数为&lt; 2 时递归将终止,因为我们知道斐波那契数列的前两项是0 和1。

    【讨论】:

      猜你喜欢
      • 2013-04-11
      • 2012-02-15
      • 2023-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 2022-11-28
      • 1970-01-01
      相关资源
      最近更新 更多