c - 测试while多种条件(C语言)

标签 c while-loop boolean-logic

我必须创建一个菜单,其中如果输入无效。它应该不断要求有效的输入。我已经在下面写了(用 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)

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

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

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

But what's happening is it loops even when the input is, for example, 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))

或者(再次关注德摩根):

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)

关于c - 测试while多种条件(C语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47369121/

相关文章:

c - 代码错误,请问是怎么回事?

c - 创建一个 for 循环来编辑数据结构中的列表

c - 如何让 execvp 函数执行每个命令行参数?

lua - 为什么 "not nil"在 Lua 中返回 true?

scala - Future中的 bool 逻辑[Boolean]

c - 使用 JSON-C 的内存泄漏

php - 使用 while 循环插入数据库

c - While 循环不断检查用户输入的整数

php - 从 MySQL 表填充动态 HTML 表

javascript - 在 javascript 中是否使用过原始变量?