|| do-while 中的条件与 &&

Conditions in do-while with || vs. &&

main()
{
    int x, y, userInput;
    do {
        {   printf("Input a number: \n");
        scanf("%i", &userInput);
        }
    } while (userInput < 1 || userInput > 50);

while 结束条件适用于 ||,我想了解为什么它不适用于 &&|| 允许我设置 0 - 50 之间的范围,如果我使用 && 它允许所有输入不受限制。这对大多数人来说很容易,但我是新手,正在努力学习基础知识。感谢任何帮助!

for (x = 1; x <= userInput; x++) {
        for (y = 1; y <= x; y++) {
            printf("*");
        }
        printf("\n");
    }
    PAUSE;
}

您想在输入小于 1 或输入大于 50 时循环。

如果使用 and,条件永远不会为真,因为输入不能小于 1 且大于 50。

因为||&&不是一个意思。

|| 是逻辑 OR 运算符,因此它在那里非常有意义,因为只有当输入为 not 时,您才 运行 再次循环你的规格。错误的输入是 userInput <1,或者 userInput >50。这两种情况都是错误的,但只有一种情况就足以让它出错,所以你使用 OR。不可能同时是 <1 和 >50,所以 AND 运算符 (&&) 总是 return false.

如果你想用 && 表示 "run the loop again only if the number is not between 1 and 50" 你必须将比较更改为:

  • while (!(userInput >= 1 && userInput <= 50));.

请注意 ! 是 NOT 运算符。