平均值不正确计算

时间:2014-01-29 18:28:32

标签: c++ mysql sql for-loop

我设计了一个小程序来计算一系列学生的平均考试成绩,然而,就我而言,无法弄清楚为什么平均值不能正常计算。发生了什么事?

输出:

  

输入课堂上的学生人数(最多50人):3   输入总测试次数(最多10个):3   输入学生1的考试成绩:   100   100   100   输入学生2的考试成绩:   100   97   75   输入学生3的考试成绩:   56   45   67   (LLDB)   (LLDB)   (lldb)

     

学生1的平均分为33.3333。 //正如你在这里看到的那样它应该是100,因为所有3个分数都是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;
}

2 个答案:

答案 0 :(得分:3)

更改

    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];
    }

否则,您将在每次添加之前重置总分数。

答案 1 :(得分:1)

您始终在内循环内将totalScore设置为0。

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

声明

            totalScore = 0.0; // why NULL?

必须放在内循环之前。

另外,我会将平均分数的计算分开并打印出结果。

所以我会写下面的方式

for ( int student = 0; student < totalStudents; student++ ) 
{
    averages[student] = 0.0;
    for ( int test = 0; test < totalTests; test++ ) 
    {
        averages[student] += score[student][test];
    }
    averages[student] /= totalTests;
}

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