为什么"或"这部分声明虽然不起作用,但是破坏声明呢?(对于C)

时间:2014-09-16 07:03:38

标签: c while-loop

学习编码,并为数字猜谜游戏尝试了一个简单的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;
    }
}

1 个答案:

答案 0 :(得分:5)

while表达式可以通过两种方式“翻译”:

  1. 只要条件成立
  2. 直到情况变为虚假
  3. 您似乎对某种稍微复杂的情况存在逻辑混淆。


    更改此内容:

    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