多条件下的while测试(C语言)



我必须创建一个菜单,其中如果输入无效。它应该一直要求一个有效的输入。我把它写在下面(用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,它也会循环。

你的代码会说:只要下列条件为真,就循环:

(input != 1 || input != 2 || input != 3 || input != 4)
如果上述条件为假,则中断循环, 为真。
!(input != 1 || input != 2 || input != 3 || input != 4)

现在让我们将德摩根定律应用于上述表达式,我们将得到逻辑相等表达式(作为循环的中断条件):

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

如果以上为真,循环将中断。当input同时等于1234时成立。这是不可能的,因此循环将永远运行。

但是即使输入是2,它也会循环。

如果input2,那么134仍然是不等的,这使得循环条件为真,继续循环。: -)


与你的问题无关:

如果你希望循环的代码至少执行一次,你应该使用do {...} while -loop。

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

或(再次跟随De Morgan):

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)

您所写的是,如果变量不是其中任何一个,则循环。你需要的是while(input < 1 || 4 < input)while(input != 1 && input != 2 && input != 3 && input != 4)

最新更新