C语言有6个学生,每个学生的数据包括学号、姓名、性别、4门课的成绩、总成绩、平均成绩。从键盘输入每个学生信息及4门课成绩,总成绩及平均成绩要通过4门课算出。然后用选择排序法按照总成绩由高到低对6个学生数据进行排序并输出排序结果。
时间: 2023-12-15 08:22:40 浏览: 59
C语言输入学生成绩,计算并输出这些学生的最低分、最高分、平均分。
下面是实现这个功能的C语言代码:
```c
#include <stdio.h>
struct Student {
int id;
char name[20];
char gender;
float scores[4];
float total_score;
float avg_score;
};
void calc_scores(struct Student *stu) {
float total_score = 0;
for (int i = 0; i < 4; i++) {
total_score += stu->scores[i];
}
stu->total_score = total_score;
stu->avg_score = total_score / 4;
}
void print_student(struct Student stu) {
printf("%d\t%s\t%c\t", stu.id, stu.name, stu.gender);
for (int i = 0; i < 4; i++) {
printf("%.1f\t", stu.scores[i]);
}
printf("%.1f\t%.1f\n", stu.total_score, stu.avg_score);
}
void sort_students(struct Student *students, int n) {
for (int i = 0; i < n - 1; i++) {
int max_index = i;
for (int j = i + 1; j < n; j++) {
if (students[j].total_score > students[max_index].total_score) {
max_index = j;
}
}
if (max_index != i) {
struct Student temp = students[i];
students[i] = students[max_index];
students[max_index] = temp;
}
}
}
int main() {
struct Student students[6];
for (int i = 0; i < 6; i++) {
printf("Enter student %d info:\n", i + 1);
printf("ID: ");
scanf("%d", &students[i].id);
printf("Name: ");
scanf("%s", students[i].name);
printf("Gender (M/F): ");
scanf(" %c", &students[i].gender);
printf("Scores (Math, English, Chinese, Programming): ");
for (int j = 0; j < 4; j++) {
scanf("%f", &students[i].scores[j]);
}
calc_scores(&students[i]);
}
printf("\nID\tName\tGender\tMath\tEnglish\tChinese\tProgramming\tTotal\tAvg\n");
for (int i = 0; i < 6; i++) {
print_student(students[i]);
}
printf("\nSorting by total score...\n");
sort_students(students, 6);
printf("\nID\tName\tGender\tMath\tEnglish\tChinese\tProgramming\tTotal\tAvg\n");
for (int i = 0; i < 6; i++) {
print_student(students[i]);
}
return 0;
}
```
这个程序定义了一个结构体 `Student`,表示一个学生的信息。在 `main` 函数中,通过循环输入6个学生的信息,并调用 `calc_scores` 函数计算总成绩和平均成绩。然后按照要求输出每个学生的信息,并调用 `sort_students` 函数排序。排序使用的是选择排序算法。最后再次输出排序后的结果。
阅读全文