C语言动态数组排序学生信息:按总分降序排列
由于题目要求使用动态数组,需要先确定存储学生信息的数据结构。一般来说,一个学生信息包括姓名、学号、三门课程成绩和总分。因此,我们可以定义一个结构体来存储这些信息:
typedef struct {
char name[20]; // 姓名
int id; // 学号
int score[3]; // 三门课程成绩
int total; // 总分
} Student;
在读取文件时,可以先统计学生人数n,然后创建一个大小为n的动态数组来存储学生信息。读取每位学生的信息时,可以使用fscanf函数来逐个读取每个字段,并将其存入动态数组中。读取完成后,可以使用qsort函数来对学生信息进行排序,排序的依据是学生的总分。最后,按照排序结果输出每位学生的信息。
下面是完整的代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[20]; // 姓名
int id; // 学号
int score[3]; // 三门课程成绩
int total; // 总分
} Student;
int cmp(const void* a, const void* b) {
const Student* s1 = *(const Student**)a;
const Student* s2 = *(const Student**)b;
return s2->total - s1->total;
}
int main() {
FILE* fp = fopen('stu.txt', 'r');
if (fp == NULL) {
printf('Failed to open file.\n');
return 1;
}
int n;
fscanf(fp, '%d', &n);
Student** students = (Student**)malloc(n * sizeof(Student*));
for (int i = 0; i < n; i++) {
students[i] = (Student*)malloc(sizeof(Student));
fscanf(fp, '%s%d%d%d', students[i]->name, &students[i]->id,
&students[i]->score[0], &students[i]->score[1], &students[i]->score[2]);
students[i]->total = students[i]->score[0] + students[i]->score[1] + students[i]->score[2];
}
qsort(students, n, sizeof(Student*), cmp);
printf('Rank\tName\tID\tScore1\tScore2\tScore3\tTotal\n');
for (int i = 0; i < n; i++) {
printf('%d\t%s\t%d\t%d\t%d\t%d\t%d\n', i+1, students[i]->name,
students[i]->id, students[i]->score[0], students[i]->score[1],
students[i]->score[2], students[i]->total);
}
for (int i = 0; i < n; i++) {
free(students[i]);
}
free(students);
fclose(fp);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/oKTR 著作权归作者所有。请勿转载和采集!