如果函数返回值,如何脱离循环
How to break out of loop if a function returned a value
这是函数:
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 中的指针值。之后,如果您调用函数检查点。如果这被改变意味着如果被调用..你可以打破你的循环。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- Python中的for循环与C++有何不同
- 如何在读取 c++ 输入时脱离循环
- 如果函数返回值,如何脱离循环
- 嵌套循环的时间复杂度:cn(n+1)/2从何而来
- 基于范围的循环与 for-each 循环有何不同
- c++ 11有没有引入新的方法来脱离嵌套的for循环?