如何不间断地提前结束一个循环

How to end a loop early without break

本文关键字:一个 循环 结束 不间断      更新时间:2023-10-16
for (int att = 1; att < 11; att++)
{
     <body>;
     //break will completely finish running the program
}

我正在制作一款CodeBreaker(Mastermind)游戏,我遇到了一个问题,即在小于11时提前结束循环,然后将循环设置回att = 1的初始化状态。

att代表"尝试"。用户可以猜测随机生成的代码最多10次。一旦用户在不到10次尝试中猜出了正确的代码,我就会提示用户再玩一次,并生成一个新的随机代码。但是上面显示的循环仍在运行。

如何提前结束循环,但仍继续运行程序?大多数程序依赖于这一个循环,因此break将完全停止它的运行。

对于set the loop back to the initialization state of att = 1,您可以使用continue:

for (int att = 1; att < 11; att++)
{
    if(you_want_to_set_loop_back) {
        att = 1;
        continue;    //It will begin the loop back with att=1, but if any other variable is modified, they will remain as it is (modified).
    }
}

你可以在一个函数中使用你想要的所有变量的初始值来编写循环。一直调用这个函数,只要你愿意。要中断循环,使用break和return from function,或者直接从循环中返回,而不是中断循环。

你可以这样做:

while(true){
    for (int att = 1; att < 11; att++)
    {
        <body>;
        //game, and when it finishes
        break;
    }
    //Asks player if he wants to continue, if not then break again
}

在for循环周围加一个while循环怎么样?

while(programRunning){
    for (int att = 1; att < 11; att++)
    {
        <body>;
        if(answer==correct){
            att = 12; // ends the for-loop
        }
    }
    if(gameOver){
        programRunning = false; // unless you want to end the game, starts the for-loop from att = 1
    }
}

我想你可以试试以下方法:

bool bQuitGame = false;
while(!bQuitGame)
{
    for(att = 1; att < 10; ++att)
    {
        if(you want to only quit "for" but stay in "while")
        {
            <code...>
            break;
        }
        else if(you want to quit "while")
        {
            <code...>
            bQuitGame = true;
            break
        }
        else if(you want to start the next iteration in "for")
        {
            <code..>
            continue;
        }
        else //you want to stay in "for"
        {
            <code...>
        }
    }
}

看来你的问题可以通过简单的嵌套循环来解决,像这样:

while(!success){
    for (int att = 1; att < 11; att++){
        <body>;
        if(answer is correct){
            success = true;
            break;
        }
        //break will completely finish running the program
    }
}