如何在嵌套循环中请求用户输入?

时间:2015-04-05 04:29:23

标签: c++ user-input nested-loops

我被赋予了显示斐波那契数字的任务,但同时询问用户他/她想要在给定时间内计算的数量。

他们告诉我这本书中有一个例子。我认为代码中的几行更改会产生我的问题的答案,但我无法理解我的代码出错了。

这是我的代码:

#include <iostream>
#include "stdafx.h"

using namespace std;

int main()
{ 

    const int NumsToCal = 5;
    cout << " This program will calculate " << NumsToCal << " Fibonacci Numbers at a time" <<endl;

    int Num1 = 0, Num2 = 1;
    char WantMore = '\0';
    cout << Num1 << " " << Num2 << " " ;

    do 
    {
        for( int Index = 0; Index < NumsToCal; ++Index)
        {
            cout << Num1 + Num2 << " ";

            int Num2Temp = Num2;
            Num2 = Num1 + Num2;
            Num1 = Num2Temp;
        }

        cout <<  "Do you want more numbers (y/n)? " << endl;
        cin >> WantMore;
    }

    while (WantMore == 'y');

        cout << "Goodbye!" << endl;


    return 0;
}

修改

#include <iostream>
#include "stdafx.h"

using namespace std;

int main()
{ 

    int NumsToCal = 5;

    cout << "How many numbers would you like to calculate?" << endl;
    cin >> NumsToCal;

    cout << " This program will calculate " << NumsToCal << " Fibonacci Numbers at a time" <<endl;

    int Num1 = 0, Num2 = 1;
    char WantMore = '\0';
    cout << Num1 << " " << Num2 << " " ;

    do 
    {
        for( int Index = 0; Index < NumsToCal; ++Index)
        {
            cout << Num1 + Num2 << " ";

            int Num2Temp = Num2;
            Num2 = Num1 + Num2;
            Num1 = Num2Temp;
        }

        cout <<  "Do you want more numbers (y/n)? " << endl;
        cin >> WantMore;
    }

    while (WantMore == 'y');

        cout << "Goodbye!" << endl;


    return 0;
}

0 个答案:

没有答案