多条件测试 while (C 语言) [英] Testing while for multiple conditions (C language)

查看:15
本文介绍了多条件测试 while (C 语言)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to create a menu wherein if the input is not valid. It should keep asking for a valid input. I've written it below (in C)

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

    while (input != 1 || input != 2 || input != 3|| input != 4)
    {
        printf("Please enter a valid option 
");
        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,它也会循环.

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

推荐答案

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

Your code is saying: Loop as long as the following is true:

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

转过来代码说:如果上述条件为假,则中断循环,对于

Turning this around the code says: Break the loop if the above condition is false, which is true for

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

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

Now let's apply De Morgan's Law to the above expression and we'll get the logical equal expression (as the loop's break condition):

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

如果上述情况成立,循环将中断.如果 input 等于 1 and 2 and 3 and 4同时.这是不可能的,所以循环将永远运行.

The loop will break if the above is true. It is true if input equals 1 and 2 and 3 and 4 at the same time. This is not possible, so the loop will run forever.

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

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

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

If input is 2 it's still unequal 1, 3 and 4, which makes the loop-condition become true and looping goes on. :-)

与您的问题无关:

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

As you want the loop's code to be execute at least once, you ought to use a do {...} while-loop.

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

或(再次跟随德摩根):

or (following De Morgan again):

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

甚至更紧:

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

这篇关于多条件测试 while (C 语言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆