Hey. I did a program that reads a file which contains names of students in a class. The names of the students are then used to read files which contain each students' grades. I then had to calculate the average of each individual student, then also calculate the average of the class and the max score and the min score of the class (not meaning the average, but each individual grade). My average isn't calculating right. It is off by a couple hundredths and I can't figure out why. Would anyone be willing to help? Thanks. Here's my code:
Code:
# include <iostream>
# include <fstream>
# include <cstdlib>
# include <string>
# include <iomanip>
using namespace std;
int main()
{
double w = -1;
string fileName, firstName, lastName, middleInitial, studName;
double countStud = 0, countSpaces = 0, x = 0;
double count = 0, min = 101, max = 0;
double classavg = 0;
double sum = 0;
cout << "Enter the name of the student file: ";
cin >> fileName;
cout << endl;
ifstream inData;
inData.open(fileName.c_str());
if (!inData)
cout << "File doesn't exist!" << endl;
else
{
cout << "First\tMI Last\t\tAverage\n" << endl;
while (inData.good())
{
inData >> lastName
>> firstName
>> middleInitial;
studName = firstName + lastName + ".dat";
count = 0; w = -1; sum = 0;
ifstream inData2;
inData2.open(studName.c_str());
if (!inData2)
cout << firstName
<< "\t"
<< middleInitial
<< " "
<< lastName
<< "\t\tNO DATA FILE"
<< endl;
else
while (inData2.good())
{
inData2 >> w;
if (w != -1)
{
count++;
if (min > w) min = w;
if (max < w) max = w;
}
sum += w;
}
inData2.close();
inData2.clear();
if (count == 0) cout << firstName
<< "\t"
<< middleInitial
<< " "
<< lastName
<< "\t"
<< "NO GRADES"
<< endl;
else
{
sum = sum / count;
classavg += sum;
countStud++;
cout << firstName
<< "\t"
<< middleInitial
<< " "
<< lastName
<< "\t\t"
<< fixed << setprecision(2) << sum
<< endl;
}
}
inData.close();
inData.clear();
classavg = classavg / countStud;
cout << endl;
cout << endl;
cout << "Max Grade = "
<< fixed
<< setprecision(2)
<< max
<< endl;
cout << "Min Grade = "
<< fixed
<< setprecision(2)
<< min
<< endl;
cout << endl;
cout << "Class Average = "
<< fixed
<< setprecision(2)
<< classavg;
}
char d;
cin >> d;
return 0;
}