我必须创建一个菜单,其中如果输入无效。它应该不断要求有效的输入。我已经在下面写了(用 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,它也会循环。
最佳答案
你的代码是这样说的:只要满足以下条件就循环:
(input != 1 || input != 2 || input != 3 || input != 4)
反过来,代码会说:如果上述条件为假,则中断循环,而对于以下情况,则为真
!(input != 1 || input != 2 || input != 3 || input != 4)
现在让我们申请De Morgan's Law到上面的表达式,我们将得到逻辑等于表达式(作为循环的中断条件):
(input == 1 && input == 2 && input == 3 && input == 4)
如果上述情况为真,则循环将中断。如果 input
等于 1
和 2
以及 3
和 4
则为 true同时。这是不可能的,因此循环将永远运行。
But what's happening is it loops even when the input is, for example, 2.
如果input
是2
,它仍然不等于1
、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))
或者(再次关注德摩根):
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 - 测试while多种条件(C语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47369121/