-5

我从第 42 行到第 47 行的程序有问题,
程序应该输出每个学生的平均值,但它给出的是 NaN 而不是平均值。

任何人都可以帮忙吗?

#include <iostream>
#include <iomanip>
using namespace std;
const int students = 3;
const int exams = 4;
int minimum( int [ ][ exams ], int, int );
int maximum( int [ ][ exams ], int, int );
double average( int [ ], int );
void printArray( int [ ][ exams ], int, int );
int main()
{
int studentGrades[ students ][ exams ] = { { 77, 68, 86, 73 }, { 96, 87, 89, 78 },
{ 70, 90, 86, 81 } };
cout << "The array is:\t";
printArray( studentGrades, students, exams );
cout << "\n\nThe highest grade is "<< maximum( studentGrades,students,exams) <<endl;
cout << "The lowest grade is "<< minimum( studentGrades,students,exams) <<endl;
cout << fixed << setprecision( 2 );
for ( int person = 0; person < students; person++ )
cout << "\nThe average grade for student " << person<< " is "<< average( studentGrades[ person ], exams );
return 0;
}
int minimum( int grades[][ exams ], int pupils, int tests )
{
int lowGrade = 100; // initialize to highest possible grade
for ( int i = 0; i < pupils; i++ )
for ( int j = 0; j < tests; j++ )
if ( grades[ i ][ j ] < lowGrade )
lowGrade = grades[ i ][ j ];
return lowGrade;
}
int maximum( int grades[][ exams ], int pupils, int tests )
{
int highGrade = 0; // initialize to lowest possible grade
for ( int i = 0; i < pupils; i++ )
for ( int j = 0; j < tests; j++ )
if ( grades[ i ][ j ] > highGrade )
highGrade = grades[ i ][ j ];
return highGrade;
}

double average( int setOfGrades[], int tests ) // here was a problem the output of the average is NaN
{
int total = 0;
for ( int i = 0; i < tests; i++ )
total += setOfGrades[ i ];
total=total/tests;
}
void printArray( int grades[][ exams ], int pupils, int tests )
{
cout << left << " [0]  [1]  [2]  [3]";
for ( int i = 0; i < pupils; i++ ) {
    cout << "\nstudentGrades[" << i << "] ";
for ( int j = 0; j < tests; j++ )
cout << setw( 5 ) << grades[ i ][ j ];
}
}
4

2 回答 2

3

你忘了归还你的总数...

double average( int setOfGrades[], int tests ) 
{
   int total = 0;
   for ( int i = 0; i < tests; i++ )
   {
      total += setOfGrades[ i ];
    }
    total=total/tests;
   return total;
}
于 2013-05-29T08:21:49.133 回答
2

您忘记return了该值,最好通过以下方式计算平均值double

double average( int setOfGrades[], int tests )
{
  double total = 0; <------------------------- double

  ...

  return total; <----------------------------- return the value
}
于 2013-05-29T08:22:36.323 回答