我无法让 getAverage 函数获得正确的平均值。我究竟做错了什么?我不能使用指针。这是原始问题:
将提示成绩并计算平均值的程序。成绩将存储在 main 中定义的名为 GradesInput 的数组中。可以存储在数组中的最大成绩数为 100。保存用户输入的实际成绩数的变量应在 main 中定义,并应称为 GradeCount。该程序将具有除 main 之外的两个功能。第一个函数应该从 main 调用,并且应该一直提示用户输入成绩,直到输入哨兵,捕获这些成绩并将它们存储在 GradesInput 中。这个函数还应该更新 main 中的变量 GradeCount,GradeCount 应该是通过引用传递的。第二个函数应该从 main 调用并且应该在 GradesInput 中找到平均成绩。平均值应该从 main 返回并打印出来。
//Lab7D This program will get the grades of students and average
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
//The 1st function should be called from main and should keep prompting the user for grades till a sentinel is entered,
//capture those grades and store them in GradesInput.
//This function should also update the variable GradeCount in main, GradeCount should have been passed by reference.
void store(int arr[], int &GradeCount) //for taking input by user pass by reference
{
int i = 0;
while (arr[i] != -1)
{
cout << "Enter grade : ";
cin >> arr[i];
GradeCount++;
}
}
//The 2nd function should be called from main and should find the average of the grades in GradesInput.
//he average should be returned to and printed out from main.
double getAverage(int arr[], int size)
{
int i;
double avg, sum = 0;
for (i = 0; i < size; i++)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
//The variable holding the actual number of grades the user entered should be defined in main and should be called GradeCount
int main()
{
int GradeCount = 0;
int grades[100];
store(grades, GradeCount);
cout << "Average : " << getAverage(grades, GradeCount) << endl;
}