我目前正在学习C,在章节结尾处的一个挑战问题是我 Build 了一个GPA计算器 . 这是挑战:
创建学生GPA平均计算器 . 该程序应提示用户输入最多30个GPA,这些GPA存储在一维数组中 . 每次他或她输入GPA时,用户都应该可以选择计算当前的GPA平均值或输入另一个GPA . 此程序的示例数据:GPA:3.5 GPA:2.8 GPA:3.0 GPA:2.5提示:小心不要将空数组元素计算到学生GPA平均值中 .
我有程序似乎有点工作,但当它计算GPA平均值时,它计算错误 . 有人请看看我的源代码,让我知道我做错了什么?
源代码
#include
int main()
{
float fGrades[30] = {0};
float fAverage = 0;
int x;
int y = 0;
float fSum = 0;
char cResp = '\0';
printf("\nGPA Calculater");
printf("\nYou can enter up to 30 grades");
do
{
printf("\nPlease enter a grade and press enter: ");
scanf("%f", &fGrades[x]);
printf("\nDo you want to calculate the GPA? (Y or N): ");
scanf("\n%c", &cResp);
} while (x < 30 && cResp != 'Y' && cResp != 'y');//end do while loop
for (x = 0; x < 30; x++)
{
fSum += fGrades[x];
}//end for loop
fAverage = fSum / x;
printf("\nYour final GPA is: %.2f\n", fAverage);
return 0;
}//end main function
我得到的输出如下:
GPA Calculater
You can enter up to 30 grades
Please enter a grade and press enter: 3.22
Do you want to calculate the GPA? (Y or N): n
Please enter a grade and press enter: 3.13
Do you want to calculate the GPA? (Y or N): n
Please enter a grade and press enter: 2.89
Do you want to calculate the GPA? (Y or N): n
Please enter a grade and press enter: 3.05
Do you want to calculate the GPA? (Y or N): y
Your final GPA is: 0.10