My class is the "review basic code" phase, as it has just started up.
The goal is to find the highest value from a file, average, and output names accordingly (see in comments).
My trouble has been with finding the max and average values within the data.
I have seen this done with vectors and arrays, but my teacher says there is an
even SIMPLER way to do this WITHOUT any of those. I have spent a considerable amount of time searching for an answer, and maybe I'm just over thinking it.
If anyone knows the simplest way to find these, I would love to know.
Any help would be GREATLY appreciated. Thanks!
int cnt = 0 ;
double highest_seen_so_far = 0 ;
double total = 0 ;
each time through the loop:
read names, and a grade
if( grade > highest_seen_so_far) highest_seen_so_far = grade ;
total += grade ; // add grade to total
++cnt ; // increment cnt
after we are done with the loop:
highest grade is the highest_seen_so_far (we have seen all)
number of grades read is cnt
total of all the grades is total
compute average grade
print out highest grade, average grade
I understand what is SUPPOSED to happen here. But after messing with it for a while, the code you suggest only gathers up the highest grade. Total and cnt do not work. I'm in the process of tinkering... for now, here is the outcome.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int cnt = 0;
double highest_seen_so_far = 0;
double total = 0;
if (grade > highest_seen_so_far) {
highest_seen_so_far = grade;
total += grade;
++cnt;
}
double average = total/cnt;//total = highest grade, cnt = 1... thus 95/1
cout << endl;
cout << "Number of grades read: " << cnt << endl;//only reads 1 grade
cout << "Highest grade: " << highest_seen_so_far << endl;//works, prints highest grade
cout << "Average grade: " << average << endl;//results from only 1 grade, prints highest grade
Ichabod Crane 89.9
Harry Potter 90.2
Frodo Baggins 78.2
Alex Cross 95
Number of grades read: 1
Highest grade: 95
Average grade: 95
Press any key to continue . . .
You don't show your loop. Nevertheless, having the "increase count and add to sum" inside conditional "do this only for entries that have higher grade than highest_seen_so_far" is clearly not what you want.
I've got the loop down. I understand now.
However, this method does not work since the grades are not in ascending order.
Therefore, when it loops and looks for "grades higher than itself", it ignores the grades lower than itself. If the grades in the file are not in ascending order, it ignores one (shown below-Frodo Baggins).