如果函数返回值,如何脱离循环

How to break out of loop if a function returned a value

本文关键字:何脱离 循环 函数 返回值 如果      更新时间:2023-10-16

这是函数:

void LoseRollDice(int Result1, int Result2, int i)
{
    if (i == 1 && (Result1 == 2 || Result1 == 3 || Result1 == 12))
    {
        cout << "You Lose." << endl;
        return;
    }
    else if (i == 1 && (Result2 == 2 || Result2 == 3 || Result2 == 12))
    {
        cout << "Computer Loses." << endl;
        return;
    }
    if (Result1 == 7 && i > 1)
    {
        cout << "You Lose." << endl;
        return;
    }
    if (Result2 == 7 && i > 1)
    {
        cout << "Computer Loses." << endl;
        return;
    }
}

在这里我使用了它:

for (int i = 1; i <= 5; i++)
{
    cout << "Enter 1 to play, or 2 to exit: ";
    cin >> chose;
    cout << endl;
    if (chose == 1)
    {
        ResultPlayer = RollDice();
        ResultComputer = RollDice();
        DisplayDice(ResultPlayer, ResultComputer, i); 
        cout << endl;
        LoseRollDice(ResultPlayer, ResultComputer, i);
        // if the player lose, how to break after this function if the condition is true in it??
        WinRollDice(ResultPlayer, ResultComputer, i, SumPlayer, SumComputer);
    }
    else break;
}

如果函数中的条件为真,如何突破 for 循环?如果我在循环中的函数之后放置 break,即使不满足条件,它也会脱离循环

将 LoseRollDice 更改为:

bool LoseRollDice(int Result1, int Result2, int i)
    {
    if (i == 1 && (Result1 == 2 || Result1 == 3 || Result1 == 12))
    {
        cout << "You Lose." << endl;
        return true;
    }
    else if (i == 1 && (Result2 == 2 || Result2 == 3 || Result2 == 12))
    {
        cout << "Computer Loses." << endl;
        return true;
    }
    if (Result1 == 7 && i > 1)
    {
        cout << "You Lose." << endl;
        return true;
    }
    if (Result2 == 7 && i > 1)
    {
        cout << "Computer Loses." << endl;
        return true;
    }
    return false;
}

然后您的其他代码执行以下操作:

for (int i = 1; i <= 5; i++)
{
    cout << "Enter 1 to play, or 2 to exit: ";
    cin >> chose;
    cout << endl;
    if (chose == 1)
    {
        ResultPlayer = RollDice();
        ResultComputer = RollDice();
        DisplayDice(ResultPlayer, ResultComputer, i); 
        cout << endl;
        if (LoseRollDice(ResultPlayer, ResultComputer, i))
            break;
        WinRollDice(ResultPlayer, ResultComputer, i, SumPlayer, SumComputer);
    }
    else break;
}

道格拉斯·道森的回答是正确的。 如果你真的真的真的希望该方法无效,你也可以让该方法抛出一个异常,然后在循环之外捕获异常。 不过,这是一种绝对糟糕的实现方式。

或者你可以在循环中捕获它并调用break;

或者使用指针...发送与函数中的参数相同的参数。更改 if 中的指针值。之后,如果您调用函数检查点。如果这被改变意味着如果被调用..你可以打破你的循环。