提示用户循环

时间:2017-08-05 06:56:44

标签: c++

我创建了一个提示用户循环以重新启动程序但是当我输入包括“y”在内的任何内容时,它只是提示我“按任意键继续......”然后关闭。这是我的代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{

    int Multiple1 = 0;
    int Multiple2 = 0;

    char again = 'Y';

    while (again == 'y' || again == 'Y')
    {

        int Multiple1 = 0;
        int Multiple2 = 0;
        cout << "Input your first Multiple: " << endl;
        cin >> Multiple1;
        cout << "Your First Multiple is: " << Multiple1 << endl;

        cout << "Input your second Multiple: " << endl;
        cin >> Multiple2;

        cout << "Your Second Multiple is: " << Multiple2 << endl;

        for (int i = 1; i <= 100; i++)
        {
            if (i % Multiple1 == 0 && i % Multiple2 == 0)
                cout << "FizzBuzz" << endl;
            else
                if (i % Multiple1 == 0)
                    cout << "Fizz" << endl;
                else
                    if (i % Multiple2 == 0)
                        cout << "Buzz" << endl;
                    else cout << i << endl;


        }

        {
            cout << "Restart? (y/n) ";
            cin >> again;



        }
        system("pause");
        return 0;
    }
}

谢谢。

这是我的第一个项目,我对编码完全不熟悉,所以我不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

您的return 0放错了地方,它应该在while循环之外。

并且您不应在{}附近放置cin >> again括号。

    { // this bracket doesn't needed
        cout << "Restart? (y/n) ";
        cin >> again;



    }

只需在需要时使用支架,例如在for, if, function, etc。它不会产生编译错误。但我认为这会让你误读,并认为while循环已经关闭。

答案 1 :(得分:0)

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{

    int Multiple1 = 0;
    int Multiple2 = 0;

    char again = 'Y';

    while (again == 'y' || again == 'Y')
    {

        int Multiple1 = 0;
        int Multiple2 = 0;
        cout << "Input your first Multiple: " << endl;
        cin >> Multiple1;
        cout << "Your First Multiple is: " << Multiple1 << endl;

        cout << "Input your second Multiple: " << endl;
        cin >> Multiple2;

        cout << "Your Second Multiple is: " << Multiple2 << endl;

        for (int i = 1; i <= 100; i++)
        {
            if (i % Multiple1 == 0 && i % Multiple2 == 0)
                cout << "FizzBuzz" << endl;
            else
                if (i % Multiple1 == 0)
                    cout << "Fizz" << endl;
                else
                    if (i % Multiple2 == 0)
                        cout << "Buzz" << endl;
                    else cout << i << endl;


        }

        { //This bracket doesn't need.
            cout << "Restart? (y/n) ";
            cin >> again;
            continue;
        } // This bracket doesn't need.
        system("pause");
        return 0;
    }
}