循环回到do while循环的开始[C ++]

时间:2018-03-14 00:53:17

标签: c++ loops while-loop do-while

我需要帮助来循环回程序的开始[C ++]。

#include <iostream>
#include <ctime>

using namespace std;

int main(int argc, char *argv[])
{
    srand(time(NULL));
    int rand_number = rand() % 101;
    int number;
    int counter = 1;


    cout << "NUMBER GUESSING" << endl;
    cout << "Try to guess number from 1 to 99: " << endl;

    do
    {
        cout << "Input number: ";
        cin >> number;
        if (number < rand_number)
        {
            cout << "Number is too small." << endl;
        }
        else
        {
            if (number > rand_number)
            {
                cout << " Number is too big." << endl;
            }
        }
        number++;

    } while (number != rand_number);
    cout << "Great! You guessed it in " << number << "th try." << endl;    

    cout << "Do you want to play again [Y/N]: ";
    cin >> Y;
    cin >> N;
 // dont know how to proceed 

    return 0;
}

当我问我是否想要再次播放并回答是“Y”时,我需要帮助回程开始,如果我回答否“N”它说再见。任何帮助将不胜感激,谢谢。

4 个答案:

答案 0 :(得分:0)

与使用do while的方式类似,尝试添加一个外部while循环来检查是否按下了N键

答案 1 :(得分:0)

你可以创建一个boolean playAgain,它将以true开头。如果玩家拒绝,则将其设置为false。然后你可以把你的做法放在另一个做的时候(playAgain)。这将循环游戏,直到玩家说他不想再玩。

答案 2 :(得分:0)

一种非常简单的方法是使用嵌套的while循环。您可以使用已有的内部循环,然后使用另一个外部来检查用户是否已放入Y。它看起来像这样:

do {
    do {
        //Get numbers and check them
        //...
    } while(number != rand_number);
    std::cout << "Some message" << std::endl;
    std::cin >> option;
} while(option != 'N');

这会循环播放,然后允许用户选择继续。如果他们选择再次进入,它会将它们带回到外部循环的顶部,并继续前进,直到他们说要停止。
修改
这将是完整的代码:

#include <iostream>
#include <ctime>

using namespace std;

int main(int argc, char *argv[])
{
    srand(time(NULL));
    char option = 'a';
    do
    {
        int rand_number = rand() % 101;
        int number;
        int counter = 1;

        std::cout << "NUMBER GUESSING" << std::endl;
        std::cout << "Try to guess number from 1 to 99: " << std::endl;

        do
        {
            std::cout << "Input number: ";
            std::cin >> number;
            if (number < rand_number)
            {
                std::cout << "Number is too small." << std::endl;
            }
            else if (number > rand_number)
            {
                std::cout << " Number is too big." << std::endl;

            }
            counter++;

        } while (number != rand_number);

        std::cout << "Great! You guessed it in " << counter << "th try." << std::endl;    
        std::cout << "Do you want to play again [Y/N]: ";
        std::cin >> option;
    } while(option !='N');

    std::cout << "Goodbye!" << std::endl;

    return 0;
}

答案 3 :(得分:0)

这不是最正统的方法,但它有效:)使用转到。

int main()
{
mylabel:

...

if( <condition> )
{
    goto mylabel;
}

...

} 

如果你想要一个更结构化的程序来编写你的主要花药函数,请说int func()并根据函数的返回循环使用。

int func()
{
    ...
    if( <condition> )
    {
        return 1;
    }
    ...
    return 0;
}

int main()
{
    while(func())
    {};
    return 0;
}