我应该编写一个程序,从文件中读取学生ID和成绩,具有3个功能:
getResults
:此函数从文件中读取并计算失败的数量(如果得分<55)计算平均值并返回学生数。
display
:向屏幕显示所有内容
isF
:检查分数是否小于55,如果分数则返回true。 (换句话说,如果学生失败,它将返回true。)
我的程序正常工作,检查有多少失败。我几乎可以肯定它是一个逻辑错误,但我无法弄清楚在哪里。未正确计算失败学生的数量。当样本文件应该是2时,我一直得到1。
#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;
}
我的示例文件如下:
- 333 95
- 123 40
- 111 88
- 121 70
- 110 55
- 909 45
示例输出:
学生人数:6
班级平均分:65
失败的学生人数:2
我获得的输出完全相同,只是我让1名学生失败。
答案 0 :(得分:3)
首先将您的numfailed
初始化为0
(感谢@ Peter),然后更改此内容:
failed = isF(studentGrade);
对此:
failed += isF(studentGrade);
或者这个:
failed += isF(studentGrade) ? 1 : 0;
答案 1 :(得分:1)
您需要更改两件事。首先将函数初始化失败归零,然后修改以添加失败次数。这是修改后的功能:
int getResults(ifstream &input, int &failed, double &average)
{
int studentID, studentGrade, total = 0, numberOfStudents = 0;
failed = 0;
while (input >> studentID >> studentGrade)
{
total = total + studentGrade;
numberOfStudents = numberOfStudents + 1;
failed += isF(studentGrade); //this ensures that every time a student fails, it is added
}
average = total / numberOfStudents;
return numberOfStudents;
}