学习编码,并为数字猜谜游戏尝试了一个简单的while循环。这个想法是,如果错误猜测的数量达到5,那么它将导致循环变为“错误”#34;并结束。相反,它将循环,直到它被测试站点作为无限循环结束。 "休息"虽然版本工作得很好。我的问题是为什么if" break"工作,但||值为set = 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;
}
}
答案 0 :(得分:5)
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