同时测试多个条件(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,它也会循环。

ALK

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

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

将代码转过来说:如果以上条件为false,则中断循环,这对于

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

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

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

如果上述情况为真,则循环将中断。如果同时input等于1and23and 4则为真这是不可能的,因此循环将永远运行。

但是发生的事情是,即使输入为2,它也会循环。

如果input是,2它仍然不相等13并且和4,这使循环条件变为true并继续循环。:-)


与您的问题无关:

由于您希望循环的代码至少执行一次,因此应该使用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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章