gpt4 book ai didi

c - 基于菜单的带有 while 和 switch 语句的程序?

转载 作者:行者123 更新时间:2023-11-30 19:52:10 24 4
gpt4 key购买 nike

我是一个初学者,我正在尝试自学。我自己写了一个 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);

}
}
}

最佳答案

试试这个:

   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 的答案以删除明显的错误。

关于c - 基于菜单的带有 while 和 switch 语句的程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24383090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com