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

查看:257
本文介绍了同时测试多个条件(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? \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,它也会循环.

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)

将其转为代码说:如果以上条件为false,则中断循环,这是正确的

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同时等于12以及34,则为真.这是不可能的,所以循环将永远运行.

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,则它仍然不等于134,这使循环条件成立,并且循环继续进行. :-)

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-循环.

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 \n");
    scanf_s("%d", &input);
} while (!(input == 1 || input == 2 || input == 3 || input == 4))

或(再次跟在De Morgan之后):

or (following De Morgan again):

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语言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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