声明一个结构体类型,其中能够存储学生的姓名、成绩(一科成绩即可)、学号; 编写函数input(),能输入 5 位学生的信息;编写函数 display(),能输出 5 位学生的信息(按成绩由高到低排序输出)。 main()函数里依次调用 input() 和 display(),完成学生信息的输入与输出。
时间: 2024-03-07 11:50:49 浏览: 28
好的,以下是代码实现:
```c
#include <stdio.h>
#include <string.h>
// 定义结构体
struct Student {
char name[20];
int score;
int id;
};
// 输入函数
void input(struct Student *students, int n) {
for (int i = 0; i < n; i++) {
printf("请输入第%d个学生的姓名:", i + 1);
scanf("%s", students[i].name);
printf("请输入第%d个学生的成绩:", i + 1);
scanf("%d", &students[i].score);
printf("请输入第%d个学生的学号:", i + 1);
scanf("%d", &students[i].id);
}
}
// 比较函数
int cmp(const void *a, const void *b) {
struct Student *s1 = (struct Student *)a;
struct Student *s2 = (struct Student *)b;
return s2->score - s1->score;
}
// 输出函数
void display(struct Student *students, int n) {
qsort(students, n, sizeof(struct Student), cmp); // 按成绩排序
printf("按成绩由高到低排序输出:\n");
for (int i = 0; i < n; i++) {
printf("姓名:%s\t成绩:%d\t学号:%d\n", students[i].name, students[i].score, students[i].id);
}
}
int main() {
struct Student students[5];
input(students, 5);
display(students, 5);
return 0;
}
```
注:本代码中使用了 `qsort()` 函数对结构体数组进行排序,需要 `#include <stdlib.h>` 头文件。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)