1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <iostream>
#include <fstream>
// read data from the input stream into the arrays, up to a maximum of max_size entries
// return the actual number of entries that were read
// input is assumed to be valid; no error checks are done
// each line of input contains three numbers: score (int or double), grade_type (int), max_score (int)
int read_scores( std::istream& stm, double score[], int type[], int max[], int max_size )
{
int cnt = 0 ; // count of actual entries read
while( cnt < max_size && stm >> score[cnt] >> type[cnt] >> max[cnt] ) ++cnt ;
return cnt ;
}
// normalise the score to a percentage (ie. max score == 100 )
// eg. normalise( 12.3, 20 ) would return 61.5 (12.3/20 == 61.5/100)
// invariant: score is non-negative, max_score is positive
double normalise( double score, int max_score ) { return score * 100.0 / max_score ; }
// return the average percentage score for a particular grade
double average_score_for_grade( const double score[], const int grade_type[], const int max_score[],
int size, int grade )
{
int num_scores = 0.0 ; // number of scores for this grade
double total_score = 0.0 ; // total scores for this grade (normalised)
for( int i = 0 ; i < size ; ++i ) // for each entry
{
if( grade_type[i] == grade ) // if the grade type is what we are looking for
{
++num_scores ;
total_score += normalise( score[i], max_score[i] ) ;
}
}
return total_score / num_scores ;
}
int main()
{
const int MAX_ENTRIES = 50 ;
double score[MAX_ENTRIES] {} ;
int grade_type[MAX_ENTRIES] {} ;
int max_score[MAX_ENTRIES] {} ;
std::ifstream file( "scores.txt" ) ; // change file name as appropriate
const int num_scores = read_scores( file, score, grade_type, max_score, MAX_ENTRIES ) ;
// num_scores scores were read from the file
if( num_scores > 0 ) // if at least one score was read
{
int grade ;
std::cout << "enter a grade type: " ;
std::cin >> grade ;
const double average = average_score_for_grade( score, grade_type, max_score, num_scores, grade ) ;
std::cout << "the average score for grade type " << grade << " is " << average << "%\n" ;
}
}
|