我是 C++ 的新手。这实际上是我正在编写的第一个类(一些代码取自 C++Primer)。尝试组合具有相同名称的类对象时出现逻辑错误。事情是这样的:
- 我的类(class)持有学生记录:姓名、通过的类(class)数和
总分(计算平均分)
构造函数从
istream
获取数据struct StudentEntry { StudentEntry() = default; StudentEntry(std::istream &); std::string getStudentName() const { return name; } StudentEntry& combine (const StudentEntry&); double avgMark() const; std::string name = ""; unsigned passCources = 0; double markSum = 0.0; };
combine
函数用于 += 数据成员(passCources
&markSum
):StudentEntry& StudentEntry::combine(const StudentEntry& st) { passCources += st.passCources; markSum += st.markSum; return *this; }
avgMark
正在计算标记平均值:double StudentEntry::avgMark() const { return passCources ? markSum / passCources : 0; }
当我在
main
中组合 2 个以上的对象时,我出错了 标记总和和平均值int main() { StudentEntry st; if (read(std::cin, st)) { StudentEntry nextSt; while (read(std::cin, nextSt)) { if (st.getStudentName() == nextSt.getStudentName()) st.combine(nextSt); } } print(std::cout, st); }
结果错误:
Next -> Nick 1 90 Next -> Nick 1 90 Next -> Nick 1 90 Next -> Nick 3 360 | Average: 120
应该是
Nick 3 270 |平均:90
我卡在这里了。
我的
print
和read
函数(和构造函数)。如果通过的类(class)数 > 1,read
应该获得所有后续分数。std::ostream& print(std::ostream &os, const StudentEntry &st) { os << st.getStudentName() << " " << st.passCources << " " << st.markSum << "\t | Average: " << st.avgMark() << "\n"; return os; } std::istream& read(std::istream &is, StudentEntry &st) { std::cout << "Next -> " << std::endl; is >> st.name >> st.passCources; double mark; for (unsigned i = 0; i < st.passCources; ++i) { is >> mark; st.markSum += mark; } return is; } StudentEntry::StudentEntry(std::istream &is) { read(is, *this); }
最佳答案
while
循环的每次迭代都会在 nextSt
中累积 markSum
值,因为它调用了 read
方法
st.markSum += mark;
你应该在迭代之前重置总和:
st.markSum = 0.0;
double mark;
for (unsigned i = 0; i < st.passCources; ++i) {
is >> mark;
st.markSum += mark;
}
关于C++ 组合从 istream 获得的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48296349/