<分区>
我正在尝试编写一个简单的程序来计算平均 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