用c语言链表知识写一个学生成绩统计程序,要求能录入学生的姓名学号成绩,并依据学生平均成绩由大到小排序输出
时间: 2024-02-01 19:14:23 浏览: 113
以下是一个基于C语言链表的学生成绩统计程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
struct student {
char name[20];
char id[10];
float score;
struct student* next;
};
// 定义链表头结点
struct student* head = NULL;
// 插入学生信息
void insert_student() {
struct student* new_node = (struct student*)malloc(sizeof(struct student));
printf("请输入学生姓名:");
scanf("%s", new_node->name);
printf("请输入学生学号:");
scanf("%s", new_node->id);
printf("请输入学生成绩:");
scanf("%f", &new_node->score);
new_node->next = head;
head = new_node;
}
// 输出学生信息
void print_students() {
struct student* current = head;
while (current != NULL) {
printf("学生姓名:%s,学号:%s,成绩:%.2f\n", current->name, current->id, current->score);
current = current->next;
}
}
// 计算平均成绩
float calc_avg_score() {
float sum = 0;
int count = 0;
struct student* current = head;
while (current != NULL) {
sum += current->score;
count++;
current = current->next;
}
return sum / count;
}
// 比较函数,用于排序
int compare_scores(const void* a, const void* b) {
struct student* s1 = *(struct student**)a;
struct student* s2 = *(struct student**)b;
if (s1->score < s2->score) {
return 1;
} else if (s1->score > s2->score) {
return -1;
} else {
return 0;
}
}
// 排序并输出
void sort_and_print_students() {
// 将链表转换为数组
int num_students = 0;
struct student* current = head;
while (current != NULL) {
num_students++;
current = current->next;
}
struct student** students_array = (struct student**)malloc(num_students * sizeof(struct student*));
current = head;
int i = 0;
while (current != NULL) {
students_array[i] = current;
current = current->next;
i++;
}
// 对数组进行排序
qsort(students_array, num_students, sizeof(struct student*), compare_scores);
// 输出排序后的学生信息
printf("按平均成绩由大到小排序后的学生信息:\n");
for (i = 0; i < num_students; i++) {
printf("学生姓名:%s,学号:%s,成绩:%.2f\n", students_array[i]->name, students_array[i]->id, students_array[i]->score);
}
// 释放数组内存
free(students_array);
}
int main() {
int choice;
do {
printf("\n");
printf("1. 插入学生信息\n");
printf("2. 输出学生信息\n");
printf("3. 计算平均成绩\n");
printf("4. 按平均成绩由大到小排序并输出\n");
printf("5. 退出程序\n");
printf("请输入您的选择:");
scanf("%d", &choice);
switch (choice) {
case 1:
insert_student();
break;
case 2:
print_students();
break;
case 3:
printf("平均成绩为:%.2f\n", calc_avg_score());
break;
case 4:
sort_and_print_students();
break;
case 5:
printf("感谢使用本程序!\n");
break;
default:
printf("无效选择,请重新输入!\n");
break;
}
} while (choice != 5);
// 释放链表内存
struct student* current = head;
while (current != NULL) {
struct student* temp = current;
current = current->next;
free(temp);
}
return 0;
}
```
该程序使用链表存储学生信息,并提供了插入、输出、计算平均成绩、排序并输出等功能。其中,排序使用了C标准库中的快速排序函数qsort(),需要传入比较函数compare_scores()进行比较。在比较函数内部,按照学生成绩从大到小排序。最后,为了避免内存泄漏,需要在程序结束时释放链表内存。
阅读全文