学习编码,并尝试使用简单的 while 循环来玩猜数字游戏。这个想法是,如果错误猜测的次数达到 5 次,就会导致循环变为“错误”并结束。相反,它会一直循环,直到被测试站点结束,因为这是一个无限循环。不过,“中断”版本工作得很好。我的问题是为什么 if “break” 有效,但 ||要设置的值= false 不起作用?
不工作的代码片段
while (secret != guess || wrong < 5)
{
if (guess < secret)
{
printf("You guessed too low\n");
wrong++;
}
else
{
printf("you guessed too high\n");
wrong++;
}
printf("Input another guess\n");
scanf ("%d", &guess);
}
工作代码片段
while (secret != guess)
{
if (guess < secret)
{
printf("You guessed too low\n");
}
else
{
printf("you guessed too high\n");
}
printf("Input another guess\n");
scanf("%d", &guess);
wrong = wrong + 1;
if (wrong >= 5)
{
break;
}
}
最佳答案
while
表达式可以通过两种方式“翻译”:
- 只要条件成立
- 直到条件变为假
您似乎对稍微复杂的条件存在逻辑困惑。
<小时/>更改此:
while (secret != guess || wrong < 5)
// until both of the conditions become false
// as long as either one of the conditions is true
对此:
while (secret != guess && wrong < 5)
// as long as both of the conditions are true
// until either one of the conditions becomes false
关于c - 为什么 while 语句的 "or"部分不起作用,但break语句却起作用?(对于 C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25862523/