Testing while for multiple conditions (C language)

和自甴很熟 提交于 2019-12-02 16:55:50

问题


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.

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


回答1:


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)

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.

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

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


Not related to your issue:

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))

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)

or even tighter:

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



回答2:


What you've written is that if the variable is not either one of them, you loop. What you want is while(input < 1 || 4 < input) or while(input != 1 && input != 2 && input != 3 && input != 4)



来源:https://stackoverflow.com/questions/39675243/testing-while-for-multiple-conditions-c-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!