有10个学生,每个学生的数据包括学号、姓名、3门功课的成绩。从键盘输入10个学生的数据,要求按平均成绩降序显示出所有学生的数据(包括学号、姓名、3门课成绩、平均成绩),并将其写入文本文件result.txt中。用C语言编写
时间: 2023-12-15 11:20:38 浏览: 55
好的,以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENT_NUM 10
#define MAX_NAME_LENGTH 20
typedef struct {
int id;
char name[MAX_NAME_LENGTH];
int score1;
int score2;
int score3;
float avg_score;
} Student;
void input_students(Student *students, int num);
void calc_avg_score(Student *students, int num);
void sort_students(Student *students, int num);
void output_students(Student *students, int num);
int main() {
Student students[MAX_STUDENT_NUM];
input_students(students, MAX_STUDENT_NUM);
calc_avg_score(students, MAX_STUDENT_NUM);
sort_students(students, MAX_STUDENT_NUM);
output_students(students, MAX_STUDENT_NUM);
return 0;
}
void input_students(Student *students, int num) {
printf("请输入%d个学生的数据:\n", num);
for (int i = 0; i < num; i++) {
printf("请输入第%d个学生的学号、姓名、3门课成绩,以空格分隔:", i + 1);
scanf("%d %s %d %d %d", &students[i].id, students[i].name, &students[i].score1, &students[i].score2, &students[i].score3);
}
}
void calc_avg_score(Student *students, int num) {
for (int i = 0; i < num; i++) {
students[i].avg_score = (float)(students[i].score1 + students[i].score2 + students[i].score3) / 3;
}
}
void sort_students(Student *students, int num) {
for (int i = 0; i < num - 1; i++) {
for (int j = i + 1; j < num; j++) {
if (students[i].avg_score < students[j].avg_score) {
Student temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
}
void output_students(Student *students, int num) {
FILE *fp = fopen("result.txt", "w");
if (fp == NULL) {
printf("无法打开文件\n");
exit(1);
}
printf("学号\t姓名\t成绩1\t成绩2\t成绩3\t平均成绩\n");
fprintf(fp, "学号\t姓名\t成绩1\t成绩2\t成绩3\t平均成绩\n");
for (int i = 0; i < num; i++) {
printf("%d\t%s\t%d\t%d\t%d\t%.2f\n", students[i].id, students[i].name, students[i].score1, students[i].score2, students[i].score3, students[i].avg_score);
fprintf(fp, "%d\t%s\t%d\t%d\t%d\t%.2f\n", students[i].id, students[i].name, students[i].score1, students[i].score2, students[i].score3, students[i].avg_score);
}
fclose(fp);
}
```
代码中使用了结构体来存储学生信息,其中 `input_students` 函数用于从键盘输入学生信息,`calc_avg_score` 函数用于计算平均成绩,`sort_students` 函数用于按平均成绩降序排序,`output_students` 函数用于显示学生信息并将其写入文件 `result.txt` 中。
阅读全文