用结构体写的…
4.将上题“stud.dat”文件中的学生数据按平均分进行降序排序处理,将已排序的学生数据存人 个新文件“stu sort.dat”中。
首先,需要读取文件中的学生信息。建议使用结构体存储学生信息,这样方便后续进行排序。
例如:
struct student{
int num; // 学号
char name[10]; // 姓名
double score[3]; // 三门课的成绩
double avg; // 平均分
}stu[5];
然后可以使用 fopen 函数打开文件,使用 fscanf 函数读取文件中的学生信息,并存储到结构体数组中。
FILE *fp = fopen("stud.dat", "r");
int i = 0;
while(fscanf(fp, "%d %s %lf %lf %lf %lf", &stu[i].num, stu[i].name, &stu[i].score[0], &stu[i].score[1], &stu[i].score[2], &stu[i].avg) == 6){
i++;
}
fclose(fp);
接下来,可以使用冒泡排序或者快速排序对学生信息进行排序。冒泡排序是稳定排序算法,快速排序是不稳定排序算法,可以根据自己的需要选择使用。
例如使用冒泡排序进行排序:
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5-i-1; j++){
if(stu[j].avg < stu[j+1].avg){
// 交换两个学生信息
struct student temp = stu[j];
stu[j] = stu[j+1];
stu[j+1] = temp;
}
}
}
使用 fopen 函数打开新文件,使用 fprintf 函数将已排序的学生信息写入文件。最后使用 fclose 函数关闭文件。
FILE *fp = fopen("stu_sort.dat", "w");
for(int i = 0; i < 5; i++){
fprintf(fp, "学号:%d\t姓名:%s\t三课:%.6f %.6f %.6f\t平均分:%.6f\n", stu[i].num, stu[i].name, stu[i].score[0], stu[i].score[1], stu[i].score[2], stu[i].avg);
}
fclose(fp);
仅供参考,望采纳,谢谢。