Bootstrap

C语言 计算学生成绩

输入10个学生5门课的成绩,分别用函数实现下列功能: 一.计算每个学生的平均分; 二.计算每门课的平均分; 三.找出所有50个分数中最高的分数所对应的学生和课程; 四.计算平均分方差: 西格玛=(1/n)*(所有xi的平方的和)-(所有xi的和/n)^2 其中,xi为某一学生的平均分。

#include <stdio.h>

#define STUDENTS 10
#define SUBJECTS 5

// 计算每个学生的平均分
void calculate_student_averages(double scores[STUDENTS][SUBJECTS], double student_averages[STUDENTS]) {
    for (int i = 0; i < STUDENTS; i++) {
        double sum = 0;
        for (int j = 0; j < SUBJECTS; j++) {
            sum += scores[i][j];
        }
        student_averages[i] = sum / SUBJECTS;
    }
}

// 计算每门课的平均分
void calculate_subject_averages(double scores[STUDENTS][SUBJECTS], double subject_averages[SUBJECTS]) {
    for (int j = 0; j < SUBJECTS; j++) {
        double sum = 0;
        for (int i = 0; i < STUDENTS; i++) {
            sum += scores[i][j];
        }
        subject_averages[j] = sum / STUDENTS;
    }
}

// 找出最高分对应的学生和课程
void find_highest_score(double scores[STUDENTS][SUBJECTS], int *student, int *subject) {
    double highest = 0;
    for (int i = 0; i < STUDENTS; i++) {
        for (int j = 0; j < SUBJECTS; j++) {
            if (scores[i][j] > highest) {
                highest = scores[i][j];
                *student = i;
                *subject = j;
            }
        }
    }
}

// 计算平均分方差
double calculate_variance(double student_averages[STUDENTS]) {
    double sum = 0, sum_squared = 0;
    for (int i = 0; i < STUDENTS; i++) {
        sum += student_averages[i];
        sum_squared += student_averages[i] * student_averages[i];
    }
    return (sum_squared / STUDENTS) - (sum / STUDENTS) * (sum / STUDENTS);
}

int main() {
    double scores[STUDENTS][SUBJECTS];
    double student_averages[STUDENTS], subject_averages[SUBJECTS];
    int highest_student, highest_subject;
    
    printf("输入10个学生5门课的成绩:\n");
    for (int i = 0; i < STUDENTS; i++) {
        for (int j = 0; j < SUBJECTS; j++) {
            scanf("%lf", &scores[i][j]);
        }
    }
    
    calculate_student_averages(scores, student_averages);
    calculate_subject_averages(scores, subject_averages);
    find_highest_score(scores, &highest_student, &highest_subject);
    double variance = calculate_variance(student_averages);
    
    printf("每个学生的平均分:\n");
    for (int i = 0; i < STUDENTS; i++) {
        printf("学生%d:%.2f\n", i+1, student_averages[i]);
    }
    
    printf("每门课的平均分:\n");
    for (int j = 0; j < SUBJECTS; j++) {
        printf("课程%d:%.2f\n", j+1, subject_averages[j]);
    }
    
    printf("最高分:学生%d,课程%d\n", highest_student + 1, highest_subject + 1);
    printf("平均分方差:%.2f\n", variance);
    
    return 0;
}

解释说明:

功能实现:

  • 函数 calculate_student_averages 计算每个学生的平均分。
  • 函数 calculate_subject_averages 计算每门课的平均分。
  • 函数 find_highest_score 找出最高分及其对应的学生和课程。
  • 函数 calculate_variance 计算学生平均分的方差。
  • 主函数从键盘输入10个学生5门课的成绩,并调用以上函数完成各项计算和结果输出。

;