You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

计算学生课程学习平均时长的C++函数无输出问题排查

问题:学生课程平均学习时长计算函数无输出

我有一份学生列表,需要为每位学生显示其3门课程的平均学习时长。所有时长已记录,只需对三个整数求平均值,但对应的函数没有输出。

main.cpp中调用函数的代码:

cout << "Average days to complete a course, by student ID:
";
for (int i = 0; i < numStudents; i++)
{
classRoster.printAverageDaysInCourse(classRoster.getStudent(i)->getStudentID());
}
cout << endl;

printAverageDaysInCourse函数实现:

void Roster::printAverageDaysInCourse(string studentID) const {
bool found = false;
for (int i = 0; i <= lastIndex; i++) {
if (classRosterArray[i]->getStudentID() == studentID) {
found = true;
const int* daysInCourse = classRosterArray[i]->getDaysInCourse();
double avgDaysInCourse = (daysInCourse[0] + daysInCourse[1] + daysInCourse[2]) / 3;
cout << "Average number of days in course for student with ID " << studentID << ": " << avgDaysInCourse << endl;
break;
}
}
if (!found) {
cout << "Error: Student with ID " << studentID << " not found in roster." << endl;
}
}

目前输出仅显示Average days to complete a course, by student ID:,无后续内容,请问是函数写法、调用方式问题,还是需要排查其他环节?


排查方向与解决建议
  • 检查numStudents的值:如果numStudents为0,外层循环根本不会执行,自然不会调用printAverageDaysInCourse函数。可以在循环前添加一行cout << "numStudents: " << numStudents << endl;确认数值是否正确。
  • 验证getStudent(i)的返回值:如果getStudent(i)返回的是空指针(nullptr),调用->getStudentID()会导致未定义行为,可能直接跳过函数调用甚至程序崩溃。可以在循环内先判断指针是否有效:
    Student* student = classRoster.getStudent(i);
    if (student != nullptr) {
        classRoster.printAverageDaysInCourse(student->getStudentID());
    } else {
        cout << "Warning: Student at index " << i << " is null." << endl;
    }
    
  • 确认lastIndex的正确性:函数内的循环条件是i <= lastIndex,如果lastIndex的值小于0(比如初始化为-1但未更新),循环不会执行,会直接进入!found分支输出错误。但你没看到错误输出,说明大概率外层循环没跑,优先检查前两点。
  • 整数除法的精度问题(次要):当前代码中(daysInCourse[0] + daysInCourse[1] + daysInCourse[2]) / 3是整数除法,结果会被截断为整数。如果需要保留小数,应该把其中一个数转为浮点数,比如(daysInCourse[0] + daysInCourse[1] + daysInCourse[2]) / 3.0,不过这不是无输出的原因,只是计算精度问题。

内容的提问来源于stack exchange,提问作者Dimming Owl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 01:12:20