暂停一个循环

时间:2014-10-18 06:10:30

标签: c++ loops while-loop fibonacci

我的代码为循环的一次迭代提供了所需的结果。在第二次迭代中,无论我要求什么斐波那契,它都会输出比要求更大的斐波那契,然后从那里输出气球。我无法弄清楚这个问题。

#include <iostream>
using namespace std;

int main ()
{
    bool exit;
    int fib;
    int fib1 = 1;
    int fib2 = 2;
    int fib3 = 0;

    cout << "The first Fibonacci number is 1" << endl;
    cout << "The second Fibonacci number is 2" << endl;
    cout << "What other Fibonacci number would you like? Enter -888 to exit: ";
    cin >> fib;

    fib = fib - 2;
    exit = fib == -888;

    while(fib--)
    {

        fib3 = (fib1+fib2);
        fib1 = fib2;
        fib2 = fib3;

        while(fib == 0)
        {

        cout << "...and the Fibonnaci is.... " << fib3 << endl;
        cout << "What other Fibonnaci would you like? Enter -888 to exit:";
        cin >> fib;

        }
    }


    return 0;
}

1 个答案:

答案 0 :(得分:0)

您的主要问题是在计算下一个数字之前没有重置fib1和fib2。

int main ()
{
    bool exit;

    cout << "The first Fibonacci number is 1" << endl;
    cout << "The second Fibonacci number is 2" << endl;

    do
    {
        int fib;
        int fib1 = 1;
        int fib2 = 2;
        int fib3 = 0;

        cout << "What other Fibonacci number would you like? Enter -888 to exit: ";
        cin >> fib;

        fib = fib - 2;
        exit = fib == -888;

        if(!exit)
        {
            while(fib--)
            {
                fib3 = (fib1+fib2);
                fib1 = fib2;
                fib2 = fib3;
            }

            cout << "...and the Fibonnaci is.... " << fib3 << endl;
        }
    } while(!exit);

    return 0;
}