C //习题 7.14 输入10个学生5门课的成绩,分别用函数实现下列功能:1.计算每个学生的平均分;2.计算每门课的平均分;3.找出所有50个分数中最高的分数所对应的学生和课程;4.计算平均分方差。
时间: 2024-12-14 20:24:24 浏览: 6
在C语言中,你可以按照以下步骤编写程序来完成这个习题:
```c
#include <stdio.h>
#include <string.h> // 用于处理字符串
// 结构体表示一个学生及其成绩
typedef struct {
char name[50];
int scores[5]; // 学生五门课的成绩
} Student;
// 计算学生的平均分
float student_average(Student student) {
float sum = 0;
for (int i = 0; i < 5; i++) {
sum += student.scores[i];
}
return sum / 5.0;
}
// 计算每门课的平均分
void course_average(int *scores, int num_students) {
float total = 0;
for (int i = 0; i < num_students; i++) {
total += scores[i];
}
printf("平均分:%.2f\n", total / num_students);
}
// 找出最高分的学生和课程
void find_highest_score(Student students[], int num_students) {
int highest_score = students[0].scores[0], max_index = 0;
for (int i = 0; i < num_students; i++) {
for (int j = 0; j < 5; j++) {
if (students[i].scores[j] > highest_score) {
highest_score = students[i].scores[j];
max_index = i;
}
}
}
printf("最高分学生:%s, 最高分课程:%d\n", students[max_index].name, max_index);
}
// 计算方差
double variance(Student students[], int num_students) {
double mean = 0;
for (int i = 0; i < num_students; i++) {
mean += student_average(students[i]);
}
mean /= num_students;
double sum_of_squares = 0;
for (int i = 0; i < num_students; i++) {
sum_of_squares += pow(student_average(students[i]) - mean, 2);
}
return sum_of_squares / num_students;
}
int main() {
Student students[10];
for (int i = 0; i < 10; i++) {
scanf("%s", students[i].name);
for (int j = 0; j < 5; j++) {
scanf("%d", &students[i].scores[j]);
}
}
// 使用函数计算并打印结果
for (int i = 0; i < 10; i++) {
printf("学生 %s 的平均分:%.2f\n", students[i].name, student_average(students[i]));
}
course_average(students[0].scores, 10);
find_highest_score(students, 10);
double overall_variance = variance(students, 10);
printf("整体平均分方差:%.2f\n", overall_variance);
return 0;
}
```
阅读全文