【发布时间】:2018-11-24 19:53:49
【问题描述】:
我正在编写一个程序来将学生的 5 分相加。
我已成功读取名为 input() 的对象函数中的 5 个整数,该函数将值分配给名为 scores 的私有 int[] 数组。
但是,我无法从 calculateTotalScore() 函数返回总和。
当我尝试运行 Eclipse 编译器时,它使用我为 scores 选择的 5 个整数给出的输出如下:
40 60 80 90 22
所以它输出的是我给它的数字,但它没有做任何整数加法。
#include <iostream>
using namespace std;
class Student {
private:
int scores[5];
int sum;
public:
void input();
int calculateTotalScore();
};
void Student::input() {
for (int i = 0; i < sizeof(scores) / sizeof(int); i++) {
int grade;
cout << "Enter your score" << endl;
cin >> grade;
scores[i] = grade;
}
//checking that the array are being stored.
for (int i=0; i < sizeof(scores) / sizeof(int);i++){
cout <<scores[i] << " " << flush;
}
cout << endl;
}
// returns the sum of the students scores
int Student::calculateTotalScore(){
for (int i=0; i < sizeof(scores) / sizeof(int);i++){
sum += scores[i];
}
return sum;
//Check that the numbers are adding up correctly
cout << sum;
}
int main() {
Student Kristen;
Kristen.input();
Kristen.calculateTotalScore();
return 0;
}
【问题讨论】:
-
您在打印总和之前从
calculateTotalScore返回。投票结束是一个错字。 -
小测验:
sum的初始值是多少,在你尝试添加所有内容之前?是0吗?是42吗?它是生命、宇宙和一切的答案吗? -
和
sum不应该是Student的成员,而是calculateTotalScore的局部变量。 -
这是在调试器中单步执行代码时很容易发现的事情之一。
-
@SamVarshavchik 好的,我已经将“sum”初始化为 0,现在它给了我正确的输出。
标签: c++ arrays function oop object