用C语言写上面的题目,编写一个函数SortStud对5个学生每个学生的3门成绩总分(由高到低)进行排序,并用new申请存放5学生数据的储存空间)
时间: 2024-04-06 10:33:12 浏览: 16
以下是用C语言实现题目要求的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
int score[3];
int total;
} student;
void SortStud(student *pstu, int n) {
int i, j;
student temp;
for (i = 0; i < n; i++) {
pstu[i].total = pstu[i].score[0] + pstu[i].score[1] + pstu[i].score[2];
}
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1 - i; j++) {
if (pstu[j].total < pstu[j + 1].total) {
temp = pstu[j];
pstu[j] = pstu[j + 1];
pstu[j + 1] = temp;
}
}
}
}
int main() {
int i, j;
student *pstu = (student *)malloc(5 * sizeof(student));
if (pstu == NULL) {
printf("Memory allocation failed.\n");
return -1;
}
printf("Please input 5 students' information:\n");
for (i = 0; i < 5; i++) {
printf("Student %d: id and 3 scores (separated by space): ", i + 1);
scanf("%d %d %d %d", &pstu[i].id, &pstu[i].score[0], &pstu[i].score[1], &pstu[i].score[2]);
}
SortStud(pstu, 5);
printf("Sorted result:\n");
for (i = 0; i < 5; i++) {
printf("Student %d, id: %d, total score: %d\n", i + 1, pstu[i].id, pstu[i].total);
printf("Scores: ");
for (j = 0; j < 3; j++) {
printf("%d ", pstu[i].score[j]);
}
printf("\n");
}
free(pstu);
return 0;
}
```
该程序定义了一个学生结构体,包含学生ID、三门成绩以及总分。函数`SortStud`用冒泡排序算法对学生按照总分进行排序。在`main`函数中,先用`malloc`申请了5个学生数据的内存空间,然后依次输入每个学生的信息,调用`SortStud`函数对学生进行排序,最后输出排序结果。注意,在程序结束时需要使用`free`函数释放动态分配的内存空间。