我是初学者,我正在努力学习。我自己写了一个switch case语句,这是基于菜单的一个。所有程序都没问题,但是当菜单重新出现时,菜单显示不正确!
代码是
int main()
{
char menu
int i,num,fact=1,d;
while(1)
{
printf("enter 'a' to find out factorial of a number\n");
printf("enter 'b' to find out that number is prime or not\n");
printf("enter 'c' to find out that number is odd or even\n");
printf("enter 'd' to exit");
scanf("%c",&menu);
switch(menu)
{
case 'a':
printf("please enter the number ");
scanf("%d",&num);
for(i=1; i<=num; i++)
fact=fact*i;
printf("factorial is %d\n",fact);
break;
case'b':
printf("enter the number");
scanf("%d",&num);
for(i=2; i<=num-1; i++)
{
if(num%i==0)
{
printf("not a prime number\n");
break;
}
}
if(i==num)
{
printf("prime number\n");
break;
}
break;
case'c':
printf("enter the number\n");
scanf("%d",&num);
d=num%2;
if(d=0)
printf("its a even number\n");
else
printf("its a odd one\n");
break;
case'd':
exit(0);
}
}
}
答案 0 :(得分:-1)
试试这个:
int ok=1;
while(1)
{
if(ok==1)
{
printf("enter 'a' to find out factorial of a number\n");
printf("enter 'b' to find out that number is prime or not\n");
printf("enter 'c' to find out that number is odd or even\n");
printf("enter 'd' to exit\n");
scanf("%c",&menu);
fflush(stdin);
}
ok=1;
switch(menu)
{
case 'a':
printf("please enter the number ");
scanf("%d",&num);
for(i=1; i<=num; i++)
fact=fact*i;
printf("factorial is %d\n",fact);
break;
......
......
default: ok=0;break;
}
}
通过此修改,菜单在我的系统上正常工作。
还要查看shekhar suman的答案,以消除明显的错误。