I'm not sure what I'm doing wrong, I have been working on this code for some time, I need to remove the lowest grade (64) and then take the average and output the grade. My code works but my average isn't correct. it is supposed to be 90.09 and not 92.4. can someone look at my code and help me fix this?
The grades are as followed:96 86 88 95 88 92 77 80 95 64 100 94
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
ifstream fin;// declare an input file stream object fin
fin.open("dat_hw5_prob1.txt");// opens a file
if (fin.is_open())// check if file opened successfully
{
double total_score = 0, min_score, score, avg_score = 0; // initialize total score and avg score to 0
int count = 0; // initialize number of scores to 0
char letter_grade;
while (fin >> score) {// read till the end of file
count++; // increment number of scores
fin >> score; // read a score from file
// if this is the first score read or score read is less than minimum score, update minimum score
if (count == 1 || (score < min_score))
{
min_score = score;
}
// add score to total score
total_score += score;
}
// subtract minimum score from total score
total_score -= min_score;
count--; // decrement number of score by 1
fin.close(); // close the file
// if number of score > 0
if (count > 0)
avg_score = (total_score) / count; // calculate average score
// determine final grade based on average score
if (avg_score >= 90)
letter_grade = 'A';
else if (avg_score >= 80)
letter_grade = 'B';
else if (avg_score >= 70)
letter_grade = 'C';
else
letter_grade = 'D';
// display the average score and final grade
cout << "Average score: " << avg_score << " final grade: " << letter_grade << endl;
}
else // file open failure
cout << "Unable to open file: dat_hw5_prob1.txt" << endl;
return 0;
}
In this line:
while (fin >> score){
You read the next score
from the file.
But 2 lines afterwards after incrementing count
you read another score
with:
fin >> score;
This line is overriding the value just read from the file (in the while(...)
), causing you to actually skip the 1st, 3rd, 5th etc. scores.
You can observe it if you add a std::cout << score << std::endl;
before accumulating the score.
In order to solve it simply remove that second read.