优化下面的代码:#include <stdio.h>#include <stdlib.h>struct student { int no; int chinese; int math; int english; double average;};int cmp(const void *a, const void *b) { struct student *s1 = (struct student*)a; struct student *s2 = (struct student*)b; if (s1->average != s2->average) { return s2->average > s1->average ? 1 : -1; // 平均分不同,按照平均分从大到小排序 } else { return s1->no - s2->no; // 平均分相同,按照学号从小到大排序 }}int main() { int n, i; scanf("%d", &n); struct student stu[n]; for (i = 0; i < n; i++) { scanf("%d %d %d %d", &stu[i].no, &stu[i].chinese, &stu[i].math, &stu[i].english); stu[i].average = (stu[i].chinese + stu[i].math + stu[i].english) / 3.0; } qsort(stu, n, sizeof(struct student), cmp); // 调用qsort函数进行排序 for (i = 0; i < n; i++) { printf("%d %d %d %d\n", stu[i].no, stu[i].chinese, stu[i].math, stu[i].english); } return 0;}
时间: 2024-01-28 12:05:00 浏览: 64
c语言函数库-第一章(C标准库).doc
您好,关于代码的优化,以下是我给出的建议:
1. 定义结构体时,可以通过宏定义来指定成员变量的名称,增加代码的可读性和可维护性。例如:
```c
#define NO no
#define CHINESE chinese
#define MATH math
#define ENGLISH english
#define AVERAGE average
struct student {
int NO;
int CHINESE;
int MATH;
int ENGLISH;
double AVERAGE;
};
```
2. 在读入学生信息时,可以使用 `fgets` 函数读入一整行字符串,然后使用 `sscanf` 函数将其转换为需要的数据类型,这样可以避免因为输入格式错误而导致的问题。例如:
```c
char line[100];
for (i = 0; i < n; i++) {
fgets(line, sizeof(line), stdin);
sscanf(line, "%d %d %d %d", &stu[i].NO, &stu[i].CHINESE, &stu[i].MATH, &stu[i].ENGLISH);
stu[i].AVERAGE = (stu[i].CHINESE + stu[i].MATH + stu[i].ENGLISH) / 3.0;
}
```
3. 在进行排序时,可以使用 `const` 限定指针参数,提高函数的安全性和可读性。例如:
```c
int cmp(const void *const a, const void *const b) {
const struct student *const s1 = (const struct student *const)a;
const struct student *const s2 = (const struct student *const)b;
if (s1->AVERAGE != s2->AVERAGE) {
return s2->AVERAGE > s1->AVERAGE ? 1 : -1; // 平均分不同,按照平均分从大到小排序
} else {
return s1->NO - s2->NO; // 平均分相同,按照学号从小到大排序
}
}
```
基于以上建议,下面是优化后的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define NO no
#define CHINESE chinese
#define MATH math
#define ENGLISH english
#define AVERAGE average
struct student {
int NO;
int CHINESE;
int MATH;
int ENGLISH;
double AVERAGE;
};
int cmp(const void *const a, const void *const b) {
const struct student *const s1 = (const struct student *const)a;
const struct student *const s2 = (const struct student *const)b;
if (s1->AVERAGE != s2->AVERAGE) {
return s2->AVERAGE > s1->AVERAGE ? 1 : -1; // 平均分不同,按照平均分从大到小排序
} else {
return s1->NO - s2->NO; // 平均分相同,按照学号从小到大排序
}
}
int main() {
int n, i;
scanf("%d", &n);
getchar(); // 吸收换行符
struct student stu[n];
char line[100];
for (i = 0; i < n; i++) {
fgets(line, sizeof(line), stdin);
sscanf(line, "%d %d %d %d", &stu[i].NO, &stu[i].CHINESE, &stu[i].MATH, &stu[i].ENGLISH);
stu[i].AVERAGE = (stu[i].CHINESE + stu[i].MATH + stu[i].ENGLISH) / 3.0;
}
qsort(stu, n, sizeof(struct student), cmp); // 调用qsort函数进行排序
for (i = 0; i < n; i++) {
printf("%d %d %d %d\n", stu[i].NO, stu[i].CHINESE, stu[i].MATH, stu[i].ENGLISH);
}
return 0;
}
```
阅读全文