[英]Basic problem of while loop in c with or operator, using to get choice from user
So the problem is very simple but I mess it up somehow.所以问题很简单,但我不知何故搞砸了。 I create a menu with this code:我用这段代码创建了一个菜单:
#include<stdio.h>
int main(){
int n;
int choice;
printf("\nMENU:\n");
printf("\n1- Add new student");
printf("\n2- Print student List");
printf("\n3- Find max average grade");
printf("\n4- Find a student by name");
printf("\n5- Delete student by ID");
printf("\n6- Export data file");
printf("\n0- Quit\n");
printf("\nPlease enter your choice: ");
scanf("%d", &choice);
fflush(stdin);
while(choice!=1 || choice!=2 || choice!=3 || choice!=4 || choice!=5 || choice!=6 || choice!=0){
printf("Please enter again: ");
scanf("%d", &choice);
fflush(stdin);
}
}
The while loop force user to only enter 1 to 6 or 0 to quit. while 循环强制用户只输入 1 到 6 或 0 退出。 However the loop will also execute when I enter those value.但是,当我输入这些值时,循环也会执行。 What have I messed up?我搞砸了什么?
I know this is a basic concept in c and I have already using it many times but this is the first time I saw this.我知道这是 c 中的一个基本概念,我已经多次使用它,但这是我第一次看到它。
Make an habit of reading C expressions out aloud/in your head, then apply common sense afterwards.养成大声/在脑海中朗读 C 表达式的习惯,然后再运用常识。
"if choice isn't 1 or it isn't 2..." Wait, that doesn't make sense. “如果选择不是 1 或者不是 2...”等等,这没有意义。
"if choise isn't 1 AND it isn't 2..." That makes sense. “如果选择不是 1 且不是 2……”这是有道理的。
Also related and generally helpful for programmers: De Morgan's Laws也相关并且对程序员通常有帮助: De Morgan's Laws
Unrelated to your question, the source of learning that told you to use fflush(stdin)
is bad and needs to be retired and replaced.与您的问题无关,告诉您使用fflush(stdin)
的学习来源很糟糕,需要退役和更换。 See Using fflush(stdin)请参阅 使用 fflush(stdin)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.