c语言选修某课程的学生有5人,学生的信息包括学号、姓名、性别、出生年月日,按学号由低到高对学生排序,输出排序后的学生信息。
时间: 2024-03-08 13:48:13 浏览: 24
好的,这是一个关于C语言的问题,我会尽力帮你解答。这道题目需要使用结构体和排序算法,下面是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
struct Student{
int id;
char name[20];
char gender[5];
char birthday[20];
};
int compare(const void *a, const void *b){
struct Student *s1 = (struct Student *)a;
struct Student *s2 = (struct Student *)b;
return s1->id - s2->id;
}
int main(){
struct Student students[5] = {
{3, "Tom", "male", "2000-01-01"},
{1, "Alice", "female", "2000-02-02"},
{5, "Bob", "male", "2000-03-03"},
{2, "Lucy", "female", "2000-04-04"},
{4, "John", "male", "2000-05-05"}
};
qsort(students, 5, sizeof(struct Student), compare);
printf("排序后的学生信息:\n");
for(int i=0; i<5; i++){
printf("学号:%d 姓名:%s 性别:%s 出生日期:%s\n", students[i].id, students[i].name, students[i].gender, students[i].birthday);
}
return 0;
}
```
输出结果为:
```
排序后的学生信息:
学号:1 姓名:Alice 性别:female 出生日期:2000-02-02
学号:2 姓名:Lucy 性别:female 出生日期:2000-04-04
学号:3 姓名:Tom 性别:male 出生日期:2000-01-01
学号:4 姓名:John 性别:male 出生日期:2000-05-05
学号:5 姓名:Bob 性别:male 出生日期:2000-03-03
```
以上代码中,首先定义了一个结构体`Student`,包含了学生的信息。然后定义了一个比较函数`compare`,用于排序。最后在`main`函数中定义了一个学生数组,将其按照学号进行排序,输出排序后的结果。