Testing while for multiple conditions (C language)

心不动则不痛 提交于 2019-12-02 10:09:36

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)

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)

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