这段代码有什么问题?斐波那契级数



它应该打印fibonacci系列直至位置,但它只是打印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;
}

您正在使用number作为循环迭代的最大数量:

while (count <= number)

,但是在循环中,您使用的变量与当前的fib值相同,以便每次迭代输出。

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

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

它就像交换变量的值。您正在使用该数字作为限制,但是在循环中,您正在使用相同的变量,该变量正在创建逻辑错误。进行以下更改,然后完成(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;
}

您可以尝试此代码:

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;
}

相关内容

最新更新