c - 为什么 while 语句的 "or"部分不起作用,但break语句却起作用?(对于 C)

标签 c while-loop

学习编码,并尝试使用简单的 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 表达式可以通过两种方式“翻译”:

  1. 只要条件成立
  2. 直到条件变为假

您似乎对稍微复杂的条件存在逻辑困惑。

<小时/>

更改此:

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/

相关文章:

c - 为什么即使我使用 float ,5/2 的结果也是 '2'?

javascript - 为什么这会导致无限循环?

C:组合 while 和 if 语句

c - while循环内存泄漏

c++ - 读取和复制中间带有 EOF 指示符的文件

c - 静态库中定义的 IRQ 符号不会覆盖 ARM/GCC 启动时的弱 IRQ 定义

c - 释放 C 中的文件写锁?

c - 如何搜索返回值位置和比较次数的数组?

file - tcl如何读取文件

R 3.4.1 - RSiteCatalyst 排队报告智能使用 while 循环