多条件同时测试(C语言)

Testing while for multiple conditions (C language)

如果输入无效,我必须创建一个菜单。它应该不断要求有效输入。我已经写在下面(用 C 语言)

   #include <stdio.h>
int main()
{
    int input = 0;
    printf("What would you like to do? \n 1 (Subtraction) \n 2 (Comparison) \n 3 (Odd/Even) \n 4 (Exit) \n ");
    scanf_s("%d", &input);

    while (input != 1 || input != 2 || input != 3|| input != 4)
    {
        printf("Please enter a valid option \n");
        scanf_s("%d", &input);
}   // At this point, I think it should keep testing variable input and if it's not either 1 or 2 or 3 or 4. It would keep looping.

但实际情况是,即使输入为 2,它也会循环。

你写的是,如果变量不是其中之一,你就循环。 你想要的是 while(input < 1 || 4 < input) 或者 while(input != 1 && input != 2 && input != 3 && input != 4)

你的代码说:只要满足以下条件就循环:

(input != 1 || input != 2 || input != 3 || input != 4)

把这个绕过代码说:如果上面的条件为假,则中断循环,这对

是正确的
!(input != 1 || input != 2 || input != 3 || input != 4)

现在让我们将 De Morgan's Law 应用到上面的表达式,我们将得到逻辑相等表达式(作为循环的中断条件):

(input == 1 && input == 2 && input == 3 && input == 4)

如果以上为真,循环将中断。如果 input 同时等于 12 以及 34,则为真。这是不可能的,所以循环将永远运行。

But what's happening is it loops even when the input is, for example, 2.

如果input2它仍然不等于134,这使得循环条件变为真并继续循环. :-)


与您的问题无关:

因为您希望循环代码至少执行一次,所以您应该使用 do {...} while 循环。

do
{
    printf("Please enter a valid option \n");
    scanf_s("%d", &input);
} while (!(input == 1 || input == 2 || input == 3 || input == 4))

或(再次关注德摩根):

do
{
    printf("Please enter a valid option \n");
    scanf_s("%d", &input);
} while (input != 1 && input != 2 && input != 3 && input != 4)

甚至更紧:

do
{
    printf("Please enter a valid option \n");
    scanf_s("%d", &input);
} while (input < 1 || input > 4)