在我的一个问题集中,我需要重写一个切换到if / else语句的程序。
该程序是为了记录输入的成绩,所以如果我输入“a”,它将统计出来,当我退出程序时,它将给用户一个输入的所有成绩的最终记录。
我有两个问题,第一个是它根本不工作,它不是将字符输入读作我设置的合法字符。第二个是如何防止其他if语句在执行正确的语句后执行。
我把它设置为if / else语句中的中断。我不确定他们是否正在工作,因为该程序显然甚至不接受这些角色。
我打算让他们转到,但原来的程序有休息,所以我用它们代替。
{
int grade;
int aCount=0;
int bCount=0;
int cCount=0;
int dCount=0;
int fCount=0;
puts( "Enter the letter grades" );
puts( "Enter EOF to end input" );
while( ( grade = getchar() ) != EOF )
{
if( grade == 'A' && grade == 'a' )
{
++aCount;
break;
}
else
{
printf( "%s\n", "That's not a valid grade, please enter again" );
break;
}
if( grade == 'B' && grade == 'b' )
{
++bCount;
break;
}
else
{
printf( "%s\n", "That's not a valid grade, please enter again" );
break;
}
if( grade == 'C' && grade == 'c' )
{
++cCount;
break;
}
else
{
printf( "%s\n", "That's not a valid grade, please enter again" );
break;
}
if( grade == 'D' && grade == 'd' )
{
++dCount;
break;
}
else
{
printf( "%s\n", "That's not a valid grade, please enter again" );
break;
}
if( grade == 'F' && grade == 'f' )
{
++fCount;
break;
}
else
{
printf( "%s\n", "That's not a valid grade, please enter again" );
break;
}
}
puts( "\nTotals for each letter grade are:" );
printf( "A: %d\n", aCount );
printf( "B: %d\n", bCount );
printf( "C: %d\n", cCount );
printf( "D: %d\n", dCount );
printf( "F: %d\n", fCount );
return 0;
}
答案 0 :(得分:4)
虽然在if语句中使用break在语法上是正确的,但它很混乱,因为它真的打破了封闭的while语句。像这样的东西更接近你正在寻找的东西:
puts( "Enter EOF to end input" );
while( ( grade = getchar() ) != EOF ) {
if( grade == 'A' || grade == 'a' )
++aCount;
else if( grade == 'B' || grade == 'b' )
++bCount;
else if( grade == 'C' || grade == 'c' )
++cCount;
else if( grade == 'D' || grade == 'd' )
++dCount;
else if( grade == 'F' || grade == 'f' )
++fCount;
else
printf( "That's not a valid grade, please enter again\n" );
}
puts( "\nTotals for each letter grade are:" );
printf( "A: %d\n", aCount );
printf( "B: %d\n", bCount );
printf( "C: %d\n", cCount );
printf( "D: %d\n", dCount );
printf( "F: %d\n", fCount );
return 0;
}
答案 1 :(得分:2)
您应该将AND(&&)条件更改为OR(||)条件,以便“A”或“a”增加aCount
变量。使用较大的if
- else if
- else
链来防止重复的错误检查。只使用字符串文字可以简化错误打印语句。
if (grade == 'A' || grade == 'a') {
++aCount;
} else if (grade == 'B' || grade == 'b') {
++bCount;
} else if (grade == 'C' || grade == 'c') {
++cCount;
} else if (grade == 'D' || grade == 'd') {
++dCount;
} else if (grade == 'F' || grade == 'f') {
++fCount;
} else {
printf("That's not a valid grade, please enter again");
}
答案 2 :(得分:1)
你的条件不能同时成立。将它们更改为OR(||)
if( grade == 'D' && grade == 'd' )
等级不能同时为D和d
答案 3 :(得分:1)
为什么不将成绩存储在数组中?
即
int grades[] = { 0, 0, 0, 0, 0 };
while( ( grade = getchar() ) != EOF )
grade = toupper(grade);
if (grade >= 'A' && grade <= 'E') {
++grades[grade - 'A'];
} else {
printf("That's not a valid grade, please enter again\n");
}
}