【发布时间】:2016-06-09 08:54:07
【问题描述】:
我正在尝试制作一个简单的程序来计算平均 GPA,但在输出过程中,这些语句并没有在它们应该停止的时候停止。我认为 printf 语句中的缓冲区没有任何问题,因为我在每个句子中都使用了新行。这在输出例如:
Enter a GPA:
9
Do you want to calculate the average GPA until now?
Press 'y' for yes or 'n' for no:
Enter a GPA:
y
Do you want to calculate the average GPA until now?
Press 'y' for yes or 'n' for no:
The average GPA is 9.0
如您所见,循环继续并再次打印出问题。
我做错了什么?
这是我的代码:
#include <stdio.h>
int main(void){
/*************************Variable declarations************************/
float fGPA;
float fUserInput = 0;
float fArray[30];
int x;
char cYesNo = '\0';
/*************************Initialize array********************************/
for(x = 0; x < 30; x++){
fGPA = 0;
printf("Enter a GPA: \n");
scanf("%f", &fUserInput);
fArray[x] = fUserInput;
fGPA += fUserInput;
printf("Do you want to calculate the average GPA until now?\n");
printf("Press 'y' for yes or 'n' for no: \n");
scanf("%c", &cYesNo);
if(cYesNo == 'y' || cYesNo == 'Y')
break;
else if(cYesNo == 'n' || cYesNo == 'N')
continue;
}//End for loop
printf("The average GPA is %.1f\n", fGPA / x);
}//End main
【问题讨论】:
-
您应该打印
cYesNo的值,以确定其中的内容。 -
'\n'!='y','y'不是要转换的有效浮点数。 -
你确实意识到整个区块
else if(cYesNo == 'n' || cYesNo == 'N') continue;什么都不做,是吗? -
@Lundin:如果您要对程序进行总体评价,为什么不提一下可能的浮点除零以及循环中累加器的归零?