针对多种条件进行测试(C语言)
我必须创建一个菜单,如果输入无效。 它应该继续要求有效的输入。 我在下面写了(在C中)
#include 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定律应用于上面的表达式,我们将获得逻辑相等的表达式(作为循环的中断条件):
(input == 1 && input == 2 && input == 3 && input == 4)
如果上述情况属实,循环将中断。 如果input
等于1
和2
以及3
和4
,则为真。 这是不可能的,因此循环将永远运行。
但是正在发生的事情是,即使输入是例如2,它也会循环。
如果input
为2
它仍然不等于3
和4
,这使得循环条件变为真并且循环继续。 🙂
与您的问题无关:
如果你想让循环代码至少执行一次,你应该使用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之后):
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)
你写的是如果变量不是其中之一,你就循环。 你想要的是while(input < 1 || 4 < input)
或while(input != 1 && input != 2 && input != 3 && input != 4)