输出上面最终优化后的代码
时间: 2024-02-25 16:53:55 浏览: 19
```c
#include <stdio.h>
#include <stdlib.h>
#define N 3 // 学生数量
#define MAX_NAME_LEN 10 // 姓名最大长度
#define MAX_SCORE 100 // 成绩最大值
#define FILENAME "stud_sort" // 文件名
struct student_type {
char name[MAX_NAME_LEN];
char num[8]; // 学号最多7位
double ave;
int score[3];
};
void print_student(struct student_type s) {
printf("%8s%8s", s.num, s.name);
for (int j = 0; j < 3; j++) {
printf("%8d", s.score[j]);
}
printf("%10.2f", s.ave);
}
int main() {
struct student_type stud[N], s;
FILE *fp, *fp1;
int i, j, insert_pos, n;
printf("NO.:");
scanf("%s", s.num);
printf("name:");
scanf("%s", s.name);
printf("score1, score2, score3:");
scanf("%d,%d,%d", &s.score[0], &s.score[1], &s.score[2]);
s.ave = (s.score[0] + s.score[1] + s.score[2]) / 3.0;
// 从文件读数据
fp = fopen(FILENAME, "r");
if (fp == NULL) {
perror("Can not open file");
exit(EXIT_FAILURE);
}
printf("original data:\n");
for (i = 0; fread(&stud[i], sizeof(struct student_type), 1, fp) != 0; i++) {
print_student(stud[i]);
putchar('\n');
}
n = i;
for (insert_pos = 0; stud[insert_pos].ave > s.ave && insert_pos < n; insert_pos++);
// 向文件写数据
printf("Now:\n");
fp1 = fopen("sort1.dat", "w");
for (i = 0; i < insert_pos; i++) {
fwrite(&stud[i], sizeof(struct student_type), 1, fp1);
print_student(stud[i]);
putchar('\n');
}
fwrite(&s, sizeof(struct student_type), 1, fp1);
print_student(s);
putchar('\n');
for (i = insert_pos; i < n; i++) {
fwrite(&stud[i], sizeof(struct student_type), 1, fp1);
print_student(stud[i]);
putchar('\n');
}
fclose(fp);
fclose(fp1);
return 0;
}
```
相关推荐
![m](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)