Heres what the program is supposed to do:
Write a program that will read data from the file "p6.dat". The file (that you will create) always contains 15 test scores (whole numbers between 0 and 100). The test scores are scores for 5 students taking 3 tests, and are arranged, in the file, by the student - that is the first 3 numbers are the test scores for test 1, 2, and 3 for the first student, etc.
The program will print:
- average per student (5 averages), on a single line, with 2 decimals
- average per test (3 averages), on a single line, with 2 decimals
- overall best score on a single line
- how many scores were As (out of the 15, how many were at least 90) on a single line
To simplify the code, no validations are needed. That is, assume the file is successfully opened, and that all data are 0-100, and that there are exactly 15 numbers in the file.
Note that the program reads the filename
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
const int num_students = 5;
const int num_tests = 3;
double testScores[num_students][num_tests];
string filename;
ifstream inputFile;
cout << "Enter name of file to read: ";
cin >> filename;
// Open the file.
inputFile.open(filename);
// Read the test scores from the file into the array.
for(int i = 0; i < num_students; i++)
{
for(int j = 0; j < num_tests; j++)
{
inputFile >> testScores[i][j];
}
}
// Close the file
inputFile.close();
// Average per student
cout << "\nAverage per student: ";
for(int i = 0; i < num_students; i++)
{
double sumForStudent = 0;
for (int j = 0; j < num_tests; j++)
{
sumForStudent = sumForStudent + testScores[i][j];
}
double avgOfStudent = sumForStudent / num_tests;
cout << "\t" << setiosflags(ios::fixed) << setprecision(2) << avgOfStudent;
}
// Average per test
cout << "\n\nAverage per test: ";
for(int i = 0; i < num_tests; i++)
{
double sumForTest = 0;
for (int j = 0; j < num_students; j++)
{
sumForTest = sumForTest + testScores[j][i];
}
double avgOfTest = sumForTest / num_students;
cout << "\t" << setiosflags(ios::fixed) << setprecision(2) << avgOfTest;
}
// Overall Best Score and number of A's
double max = 0, countOfA = 0;
for(int i = 0; i < num_students; i++)
{
for (int j = 0; j < num_tests; j++)
{
if(testScores[i][j] > max)
max = testScores[i][j];
if(testScores[i][j] >= 90)
++countOfA;
}
}
cout << "\n\nOverall best score: " << max;
cout << "\n\nNumber of A's: " << countOfA << "\n\n";
system("pause");
return 0;
}
|
And all I get when I run is:
Average per student: 0.00 0.00 nan 0.00 0.00
Average per test: 0.00 0.00 nan
Overall best score: 0.00
Number of A's: 0.00