gpt4 book ai didi

c++ - 平均值计算不正确

转载 作者:行者123 更新时间:2023-11-27 23:08:56 25 4
gpt4 key购买 nike

我设计了一个小程序来计算一组学生的平均考试成绩,但是,对于我来说,无法弄清楚为什么平均数计算不正确。这是怎么回事?

输出:

Enter number of students in class (max 50): 3 Enter total number of tests (max 10): 3 Enter student 1's test scores: 100 100 100 Enter student 2's test scores: 100 97 75 Enter student 3's test scores: 56 45 67 (lldb) (lldb) (lldb)

The average score for student 1 is 33.3333. // As you see here it should be 100 since all 3 scores were 100. (lldb)

代码:

const int MAX_STUDENTS = 50;
const int MAX_TESTS = 10;

int main()
{
char studentName[50];
int totalStudents = 0;
int totalTests = 0;
double totalScore = 0;
double score[MAX_STUDENTS][MAX_TESTS];
double averages[MAX_STUDENTS];

std::cout << "Enter number of students in class (max " << MAX_STUDENTS << "): ";
std::cin >> totalStudents;
std::cout << "Enter total number of tests (max " << MAX_TESTS << "): ";
std::cin >> totalTests;
for (int student = 0; student < totalStudents; student++) {
std::cout << "Enter student " << (student + 1) << "'s test scores: " << endl;
for (int test = 0; test < totalTests; test++) {
std::cin >> score[student][test];
}
}

for (int student = 0; student < totalStudents; student++) {
for (int test = 0; test < totalTests; test++) {
totalScore = NULL;
totalScore += score[student][test];
}
averages[student] = totalScore / totalTests;
std::cout << endl;
std::cout << "The average score for student " << student + 1 << " is " << averages[student] << "." << endl;
}

return 0;
}

最佳答案

改变

    for (int test = 0; test < totalTests; test++) {
totalScore = NULL;
totalScore += score[student][test];
}

    totalScore = 0;
for (int test = 0; test < totalTests; test++) {
totalScore += score[student][test];
}

否则,您将在每次添加之前重置 totalScore。

关于c++ - 平均值计算不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21439530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com