优化下面的代码:#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct{ int id; int chinese; int math; int english; float average;}Student;int cmp(const void* a, const void* b){ Student* s1 = (Student*)a; Student* s2 = (Student*)b; if(s1->average != s2->average){ return s2->average - s1->average; }else{ return s1->id - s2->id; }}int main(){ int n; scanf("%d", &n); Student students[n]; memset(students, 0, sizeof(students)); for(int i = 0; i < n; i++){ scanf("%d %d %d %d", &students[i].id, &students[i].chinese, &students[i].math, &students[i].english); students[i].average = (float)(students[i].chinese + students[i].math + students[i].english) / 3; } qsort(students, n, sizeof(Student), cmp); for(int i = 0; i < n; i++){ printf("%d %d %d %d\n", students[i].id, students[i].chinese, students[i].math, students[i].english); } return 0;}
时间: 2024-01-23 19:04:17 浏览: 134
SeqList.h #include <stdio.h> //包含标准输入输出流的头文件 #include <assert.h
以下是优化后的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int id;
int chinese;
int math;
int english;
float average;
}Student;
int cmp(const void* a, const void* b){
Student* s1 = (Student*)a;
Student* s2 = (Student*)b;
if(s1->average != s2->average){
return s2->average > s1->average ? 1 : -1;
}else{
return s1->id - s2->id;
}
}
int main(){
int n;
scanf("%d", &n);
Student *students = (Student*)malloc(n * sizeof(Student));
for(int i = 0; i < n; i++){
scanf("%d %d %d %d", &students[i].id, &students[i].chinese, &students[i].math, &students[i].english);
students[i].average = (float)(students[i].chinese + students[i].math + students[i].english) / 3;
}
qsort(students, n, sizeof(Student), cmp);
for(int i = 0; i < n; i++){
printf("%d %d %d %d\n", students[i].id, students[i].chinese, students[i].math, students[i].english);
}
free(students);
return 0;
}
```
该程序对原程序进行了如下优化:
1. 在结构体定义中去掉了头文件`string.h`的引用,因为该头文件并未被使用到。
2. 在比较函数`cmp`中,将`s2->average - s1->average`的判断改为了`s2->average > s1->average ? 1 : -1`的形式,因为前者可能会出现溢出的问题,而后者则可以避免这种情况的发生。
3. 在主函数中,使用了动态分配内存的方式来申请学生结构体数组,这样可以避免在编译时需要定义数组大小的问题。
4. 在程序结尾处,使用了`free`函数来释放动态分配的内存,避免内存泄漏的问题。
阅读全文