练习7:输入n(4<=n<=20)个学生m(2<=m<=5)门课程的成绩,分别求每个学生的平均成绩和每门课程的平均成绩并显示,并根据输入的科目序号j(1<=j<=m)和排名i(1<=i<=n),将第j个科目的前i个成绩从高到低排序显示。以上功能均书写函数实现。
时间: 2024-10-20 14:08:53 浏览: 23
好的,我们可以创建几个C语言函数来实现这个需求。首先,我们需要定义结构体表示学生和课程信息,然后编写函数来接收输入、计算平均分以及对成绩进行排序。以下是一个可能的实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义结构体表示学生和课程
typedef struct {
int id;
float scores[20]; // 假设最多有20门课
} Student;
typedef struct {
char name[20];
Student *students;
int num_students;
} Course;
// 函数用于计算学生平均成绩
float calculate_student_average(Student *student, int m) {
float sum = 0;
for (int i = 0; i < m; i++) {
sum += student->scores[i];
}
return sum / m;
}
// 函数用于计算课程平均成绩
float calculate_course_average(Course *course) {
float total_sum = 0;
for (int i = 0; i < course->num_students; i++) {
for (int j = 0; j < 20; j++) { // 注意这里假设课程只用到了学生数组的一部分
if (j < course->students[i].scores[course->students[i].id]) {
total_sum += course->students[i].scores[j];
}
}
}
return total_sum / (course->num_students * 20);
}
// 对特定科目和排名排序成绩
void sort_scores_by_subject_and_rank(int j, int i, Course *course) {
for (int k = 0; k < course->num_students; k++) {
for (int l = 0; l < i - 1; l++) {
if (course->students[k].scores[j - 1] < course->students[l].scores[j - 1]) {
float temp = course->students[k].scores[j - 1];
course->students[k].scores[j - 1] = course->students[l].scores[j - 1];
course->students[l].scores[j - 1] = temp;
}
}
}
}
int main() {
int n, m, j, i;
printf("Enter the number of students (4 <= n <= 20): ");
scanf("%d", &n);
Course course;
course.students = malloc(n * sizeof(Student));
course.num_students = n;
for (int s = 0; s < n; s++) {
printf("Enter student %d's ID: ", s + 1);
scanf("%d", &course.students[s].id);
for (int c = 0; c < m; c++) {
printf("Enter score for subject %d: ", c + 1);
scanf("%f", &course.students[s].scores[c]);
}
}
printf("\nAverage scores by student:\n");
for (int s = 0; s < n; s++) {
float avg = calculate_student_average(&course.students[s], m);
printf("Student %d: %.2f\n", s + 1, avg);
}
printf("\nAverage scores by course:\n");
float avg_course = calculate_course_average(&course);
printf("Average score across all subjects: %.2f\n", avg_course);
printf("\nEnter subject number (1-%d) and ranking (1-%d): ", m, n);
scanf("%d %d", &j, &i);
sort_scores_by_subject_and_rank(j - 1, i, &course);
printf("\nTop %d scores for subject %d:\n", i, j);
for (int s = 0; s < i; s++) {
printf("Student %d: %.2f\n", course.students[s].id, course.students[s].scores[j - 1]);
}
free(course.students);
return 0;
}
```
阅读全文