I'm supposed to write a program that reads student IDs and grades from a file, with 3 functions:
getResults: this function reads from the file and counts how many failed (if score < 55) calculates the average and returns the number of students.display: displays everything to the screenisF: checks whether the score is less than 55 and returns true if it is. (In other words, if the student failed it will return true.)
My program is working fine up to the checking how many failed. I'm almost certain its a logical error but I can't figure out where. The number of failed students is not being calculated correctly. I keep getting 1 when it is supposed to be 2 as per the sample file.
#include <iostream>
#include <fstream>
using namespace std;
int getResults(ifstream &input, int &failed, double &average);
bool isF(int score);
void display(int num_students, double average, int num_failed);
int main() {
int numfailed, numOfStudents;
double avg;
ifstream in_stream("grades.txt");
numOfStudents = getResults(in_stream, numfailed, avg);
display(numOfStudents, avg, numfailed);
system("PAUSE");
return 0;
}
int getResults(ifstream &input, int &failed, double &average) {
int studentID, studentGrade, total = 0, numberOfStudents = 0;
while (input >> studentID >> studentGrade) {
total = total + studentGrade;
numberOfStudents = numberOfStudents + 1;
failed = isF(studentGrade);
}
average = total / numberOfStudents;
return numberOfStudents;
}
bool isF(int score) {
if (score < 55)
return true;
else
return false;
}
void display(int num_students, double average, int num_failed) {
cout << "Number of Students: " << num_students << endl;
cout << "Class Average: " << average << endl;
cout << "Number of students failed: " << num_failed << endl;
}
My sample file is as follows:
- 333 95
- 123 40
- 111 88
- 121 70
- 110 55
- 909 45
Sample output:
Number of students: 6
Class Average: 65
Number of students failed: 2
The output I'm getting is exactly the same except that I get 1 student failed.
if (score < 55) return true; else return false;withreturn (score < 55);. But you aren't counting failures.