[英]do-while loop into for loop
I made a game but didn't wanted to use do-while loops.我做了一个游戏,但不想使用 do-while 循环。 So instead I tried to use for loops.所以我尝试使用 for 循环。 The problem is when I run with do-while it works but when I run with for loops it doesn't work in the same way.问题是当我使用 do-while 运行时它可以工作,但是当我使用 for 循环运行时它不会以相同的方式工作。
I think I changed do-while into for loops correctly.我想我正确地将 do-while 更改为 for 循环。 Can someone let me know what I am missing?有人可以让我知道我错过了什么吗?
do {
crntShowBottle = rand() % 2 + 2;
} while (crntShowBottle == prevShowBottle);
prevShowBottle = crntShowBottle;
for (;;)
{
crntShowBottle = rand() % 2 + 2;
if (crntShowBottle == prevShowBottle)
break;
}
prevShowBottle = crntShowBottle;
First, try to understand the mechanism of loop
and how they are different from do-while loop
and for loop
.首先,尝试了解loop
的机制以及它们与do-while loop
和for loop
的不同之处。
Based on your code, what is happening!根据您的代码,发生了什么!
In the do-while
section, you are giving instructions that "first do something" and then checking the condition.在do-while
部分,您给出了“首先做某事”然后检查条件的说明。 If the condition (checking) is true
crntShowBottle == prevShowBottle
then the loop must run again.如果条件(检查)为true
crntShowBottle == prevShowBottle
则循环必须再次运行。 Otherwise, if the condition is false
crntShowBottle != prevShowBottle
the loop must terminate.否则,如果条件为false
crntShowBottle != prevShowBottle
循环必须终止。
In the for loop
section, you used the infinite loop
for(;;)
.在for loop
部分,您使用了infinite loop
for(;;)
。 Means loop will be running infinite times.意味着循环将无限次运行。 But, inside the loop
you wrote the break
condition.但是,在loop
中你写the break
条件。 So, when the condition is matching crntShowBottle == prevShowBottle
your loop is shutting down.因此,当条件匹配crntShowBottle == prevShowBottle
时,您的循环将关闭。 So, you must use crntShowBottle != prevShowBottle
所以,你必须使用crntShowBottle != prevShowBottle
You also need to understand, how break
works!您还需要了解break
的工作原理!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.