如何不间断地提前结束一个循环
How to end a loop early without break
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
}
}
相关文章:
- 使用一个循环与两个循环
- 如何通过一个循环将多个文件的内容分配给不同的类属性?
- 我对C++很陌生,我被困在试图做一个循环
- 该程序没有产生输出,而是卡在一个循环中,几秒钟后消失并打印被杀死?
- 有没有办法把它变成一个循环,让它更具包容性?
- 是否可以在一个循环中写入多个二进制文件
- C++在最后一个循环中排除了部分循环运算符
- 是否可以为一个循环设置多个条件
- 创建一个循环,该循环将输出大于零且小于 60(不包括 60)的所有 5 的倍数
- 如何创建一个循环,该循环检查每次迭代并在每次迭代后从头开始
- 如何在一个循环中分离两个不同的数组?
- 为什么这个do-while循环每隔一个循环只写入数组?
- 我在 c ++ 中有一个循环错误
- C :使用文件末端(CTRL Z)结束一个循环似乎打破了我程序的其余部分
- 如何将枯竭的健康转移到下一个循环中
- 一个循环,可以打印所有项目(无论链条多长时间) *指针
- 在 GtkDialog 中创建一个循环
- 我可以做一个循环,直到“std::cin”在输入缓冲区中看到“”字符
- 一个线程设置成员,而另一个循环上方 - 是此螺纹 - 不安全
- 编写一个循环,以检查变量的值与大量可能的有效值(C )的值