在 do while 循环中 && 运算符的正确用法是什么?

What's the propper use of && operator in a do while loop?

我不明白为什么程序只为大于 9 的值定义 Heigth,如果有人能指出我的错误,我将非常高兴,谢谢您的宝贵时间。

#include <cs50.h>
include <stdio.h>

int Heigth;

int main(void) { 
    do { 
        Heigth = get_int("A level value please ? ");    
    } while (9 > Heigth && Heigth > 0); 

    printf("Heigth is %d", Heigth);
} 

输出:

$ ./mario
A level value please ? 5
A level value please ? 7
A level value please ? 98
Heigth is 98$ ^C

代码片段:

do {
    something();
} while (condition1 && condition2);

表示如果condition1condition2都为真,则重复something()。在您的情况下,如果 Height 介于 9 和 0 之间,将重复调用 get_int()。也就是说,9 > HeightHeight > 0 都为真。

如果您实际上想要在 Height 大于 8 或小于 1 时重复调用 get_int,那么您必须编写条件来说明这一点。但是,那么您就不会使用 &&。你会写成8 < Height || Height < 1

在布尔逻辑中,¬(A ∧ B) ≡ (¬A ∨ ¬B) 为真,因此您可以通过取反原始表达式来获得等效的行为。

do {
    something();
} while (!(condition1 && condition2));

在任何条件循环中使用&&就是加入条件。

在您的程序中,您指定当同时满足 9 > HeigthHeigth > 0 条件时,该循环将自行重复。

9 > Heigth 并不是通常的格式,通常变量出现在文字之前,因此最好使用 Heigh < 9.

所以要将其翻译成文本,这意味着当输入的数字小于 9 并且大于 0 时,循环将自行重复,因此值范围为 2 到 8,包括。

如果输入不满足条件的数,则循环结束,程序继续执行下一条指令,此时退出。