float findGradeAvg(GradeType array, int numOfGrades)
{
float sum = 0;
for (int i = 0; i < numOfGrades; i++)
sum = sum + array[i];
return (sum / numOfGrades);
}
以上是我查找输入成绩平均值的代码。功能骨架无法更改,因此我无法使用浮动和两个输入。
这是我的主要内容:
int main()
{
StringType30 firstname, lastname; // two arrays of characters defined
int numOfGrades; // holds the number of grades
GradeType grades; // grades is defined as a one dimensional array
float average; // holds the average of a student's grade
char moreinput; // determines if there is more input
// Input the number of grades for each student
cout << "Please input the number of grades each student will receive." << endl
<< "This number must be a number between 1 and " << MAXGRADE << " inclusive" << endl;
cin >> numOfGrades;
while (numOfGrades > MAXGRADE || numOfGrades < 1)
{
cout << "Please input the number of grades for each student." << endl
<< "This number must be a number between 1 and " << MAXGRADE << " inclusive" << endl;
cin >> numOfGrades;
}
// Input names and grades for each student
cout << "Please input a y if you want to input more students"
<< " any other character will stop the input" << endl;
cin >> moreinput;
while ( moreinput == 'y' || moreinput == 'Y')
{
cout << "Please input the first name of the student" << endl;
cin >> firstname;
cout << endl << "Please input the last name of the student" << endl;
cin >> lastname;
for (int count = 0; count < numOfGrades; count++)
{
cout << endl << "Please input a grade" << endl;
int i = 0;
cin >> grades[i];
i++;
}
cout << firstname << ' ' << lastname << " has an average of ";
float average = findGradeAvg(grades, numOfGrades);
cout << average;
cout << "which gives the letter grade of " << findLetterGrade(average);
cout << endl << endl << endl;
cout << "Please input a y if you want to input more students"
<< " any other character will stop the input" << endl;
cin >> moreinput;
}
system("pause");
return 0;
}
我不知道为什么它给出了不正确的平均值,因为我在具有正确结果的不同程序中使用了此函数。现在我输入100,90和90,并收到以下作为输出。
-7.15828e + 007
答案 0 :(得分:5)
这是一个问题
for (int count = 0; count < numOfGrades; count++)
{
cout << endl << "Please input a grade" << endl;
int i = 0;
cin >> grades[i];
i++;
}
在这里你定义(并一遍又一遍地重新定义)循环中的变量i
!这意味着i
将始终为零。你可能想要例如。
cin >> grades[count];