【问题标题】:What's wrong with this code? Fibonacci series这段代码有什么问题?斐波那契数列
【发布时间】:2018-09-09 12:25:39
【问题描述】:

它应该打印斐波那契数列直到一个位置,但它只打印 1 1 2,即使我要求的不仅仅是前三个元素。我该如何解决这个问题?

#include <iostream>
using std::cout;
using std::cin;

int main()
{
    cout << "Enter a number: ";
    int number;
    cin >> number;
    int count = 1;
    int a = 1;                  //The first number of the Fibonacci's serie is 1
    int b = 1;                  //The second number of the Fibonacci's serie is 2
    while (count <= number)
    {
        if (count < 3)
            cout << "1 ";
        else
        {
            number = a + b;     //Every number is the sum of the previous two
            cout << number << " ";
            if (count % 2 == 1)
                a = number;
            else
                b = number;
        }
        count++;
    }

    return 0;
}

【问题讨论】:

    标签: c++ fibonacci dev-c++


    【解决方案1】:

    你可以试试这个代码:

    int main()
    {
        int n, t1 = 0, t2 = 1, nextTerm = 0;
    
        cout << "Enter the number of terms: ";
        cin >> n;
    
        cout << "Fibonacci Series: ";
    
        for (int i = 1; i <= n; ++i)
        {
          // Prints the first two terms.
            if(i == 1)
            {
                cout << " " << t1;
                continue;
            }
            if(i == 2)
            {
                cout << t2 << " ";
                continue;
           }
            nextTerm = t1 + t2;
            t1 = t2;
            t2 = nextTerm;
    
            cout << nextTerm << " ";
        }
        return 0;
    }
    

    【讨论】:

    • 这可能真的很有帮助,尤其是对于未来的用户来说,与其他答案相比,它实际上说明了为什么它有效。 Bills answer 的代码较少,但实际上告诉 OP 为什么他的帖子确实有效。
    【解决方案2】:

    这就像交换变量的值。 您使用数字作为限制,但在循环中您使用的是创建逻辑错误的相同变量。进行以下更改即可完成 (Y)。

    int main()
    {
    cout << "Enter a number: ";
    int number;
    cin >> number;
    int count = 1;
    int a = 1;                  //The first number of the Fibonacci's serie is 1
    int b = 1; 
    int i = 1;                 //The second number of the Fibonacci's serie is 2
    while (i <= number)
    {
        if (i < 3)
            cout << "1 ";
        else
        {
            count = a + b;     //Every number is the sum of the previous two
            a = b;
            b = count;
            cout << count << " ";
        }
        i++;
    }
    
    return 0;
    }
    

    【讨论】:

      【解决方案3】:

      您在这里使用number 作为循环迭代的最大次数:

      while (count <= number)
      

      但是在循环内部,您使用与当前 Fib 值相同的变量来输出每次迭代。

      number = a + b;     //Every number is the sum of the previous two
      cout << number << " ";
      

      这会导致循环过早终止。您需要为这两个不同的值选择不同的变量名称。

      【讨论】:

        猜你喜欢
        • 2015-09-29
        • 2011-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 1970-01-01
        • 2021-09-15
        • 1970-01-01
        相关资源
        最近更新 更多