用结构体输入各学生信息,各学生按学号和总成绩分别升序排
时间: 2024-05-04 07:22:17 浏览: 94
学生信息排序
下面是一个示例代码,用结构体输入学生信息并按照学号和总成绩排序:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 100
struct student {
char id[10];
char name[20];
int score1;
int score2;
int score3;
int total;
};
int main() {
struct student students[MAX_STUDENTS];
int n = 0;
printf("Enter number of students: ");
scanf("%d", &n);
// 输入每个学生的信息
for (int i = 0; i < n; i++) {
printf("Enter student %d's ID, name, score1, score2, score3: ", i+1);
scanf("%s %s %d %d %d", students[i].id, students[i].name,
&students[i].score1, &students[i].score2, &students[i].score3);
students[i].total = students[i].score1 + students[i].score2 + students[i].score3;
}
// 按学号升序排序
for (int i = 0; i < n-1; i++) {
for (int j = i+1; j < n; j++) {
if (strcmp(students[i].id, students[j].id) > 0) {
struct student temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
printf("\nSorted by ID:\n");
printf("ID\tName\tScore1\tScore2\tScore3\tTotal\n");
for (int i = 0; i < n; i++) {
printf("%s\t%s\t%d\t%d\t%d\t%d\n", students[i].id, students[i].name,
students[i].score1, students[i].score2, students[i].score3, students[i].total);
}
// 按总成绩升序排序
for (int i = 0; i < n-1; i++) {
for (int j = i+1; j < n; j++) {
if (students[i].total > students[j].total) {
struct student temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
printf("\nSorted by total score:\n");
printf("ID\tName\tScore1\tScore2\tScore3\tTotal\n");
for (int i = 0; i < n; i++) {
printf("%s\t%s\t%d\t%d\t%d\t%d\n", students[i].id, students[i].name,
students[i].score1, students[i].score2, students[i].score3, students[i].total);
}
return 0;
}
```
在这个示例代码中,我们使用了一个结构体 `student` 来表示每个学生的信息。每个学生包括学号、姓名、三门科目的成绩以及总成绩。我们首先输入每个学生的信息,然后按照学号进行升序排序并输出,接着按照总成绩进行升序排序并输出。在排序过程中,我们使用了 `strcmp` 函数来比较两个学生的学号的大小关系。
阅读全文