gpt4 book ai didi

c - 带有嵌套开关的 while 循环没有输出

转载 作者:行者123 更新时间:2023-11-30 20:03:37 25 4
gpt4 key购买 nike

#include <stdio.h>
int main()
{
char cha;
int m=0;
int f=0;
int tot;
while(cha=='m'||cha=='M'||cha=='F'||cha=='f')
{
printf("What is your gender?(m or f):\n");
scanf(" %c",&cha);
switch (cha)
{
case 'm':
case 'M':
printf("\nYou are a male");
++m;
printf("\nPress a to total up");
break;

case 'f':
case 'F':
printf("\nYou are a female");
++f;
printf("\nPress a to total up");
break;

case 'a':
tot=m+f;
printf("\nThe number of male is %d and the number of female is %d",m,f);
printf("\nThe total of male and female is:%d",tot);
break;
}

}

return 0;

}

所以我只是乱搞我的代码,试图建立一个程序,可以总结程序中输入的 m 和 f 的数量,最终根本没有输出。程序刚刚终止,没有显示任何输出。我尝试在 while 表达式末尾添加分号,但 while 循环最终甚至无法运行。我的代码有什么问题吗?

最佳答案

你没有给 cha 一个值。所以它不会进入 while 。我认为这个版本更好。而且错误处理也非常重要。

#include <stdio.h>
int main()
{

char cha;
int m=0;
int f=0;
int tot;
bool end = false;
while(end==false)
{
printf("What is your gender?(m or f):\n");
scanf(" %c",&cha);

switch (cha)
{
case 'm':
case 'M':
printf("\nYou are a male");
++m;
printf("\nPress a to total up");
break;

case 'f':
case 'F':
printf("\nYou are a female");
++f;
printf("\nPress a to total up");
break;

case 'a':
tot=m+f;
end = true;
printf("\nThe number of male is %d and the number of female is %d",m,f);
printf("\nThe total of male and female is:%d",tot);
break;

default:
printf("\nEnter valid sex.");
}

}

return 0;

关于c - 带有嵌套开关的 while 循环没有输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48682698/

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