#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循环结束甚至不起作用。我的代码出了什么问题?
答案 0 :(得分:2)
这个循环表达式:
while(cha=='m'||cha=='M'||cha=='F'||cha=='f')
在 cha
通过调用scanf()
给出值之前评估。所以基本上你会得到随机行为,因为cha
在首次达到该行时未初始化。它保存任何有效字符的可能性非常低,可以立即退出循环。
此外,请注意scanf()
可能会失败;你应该经常检查它的返回值。
答案 1 :(得分:1)
#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;
答案 2 :(得分:0)
虽然条件永远不会成真
永远不会成真你应该根据你修改它来工作,虽然我修改了你的代码你可以看看它。
`#include <stdio.h>
int main()
{
char cha;
int m=0;
int f=0;
int tot;
while(cha!='a')
{
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;
`}
答案 3 :(得分:0)
嗨,你的while循环永远不会满足,因为cha在while循环之前从未初始化。根据您的要求,它应该是do while loop
而不是while loop
。修改您的代码如下: -
int main()
{
char cha;
int m=0;
int f=0;
int tot;
do
{
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;
}
} while(cha=='m'||cha=='M'||cha=='F'||cha=='f');
return 0;
}