编写程序,定义一个结构体类型,包含char name[20]成绩 int score子元素,定义10个元素的结构体数组,输入10个同学的信息,按成绩由大到小排序
时间: 2024-01-25 17:05:14 浏览: 28
可以使用以下代码定义一个包含 `char name[20]` 和 `int score` 成员的结构体类型,并定义一个包含 10 个元素的结构体数组。
```c
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int score;
};
int main() {
struct Student students[10];
int i, j, max_idx;
struct Student temp;
// 输入学生信息
for (i = 0; i < 10; i++) {
printf("请输入第 %d 个学生的姓名和成绩:", i+1);
scanf("%s %d", students[i].name, &students[i].score);
}
// 按成绩由大到小排序
for (i = 0; i < 10; i++) {
max_idx = i;
for (j = i + 1; j < 10; j++) {
if (students[j].score > students[max_idx].score) {
max_idx = j;
}
}
if (max_idx != i) {
temp = students[i];
students[i] = students[max_idx];
students[max_idx] = temp;
}
}
// 输出排序后的学生信息
printf("按成绩由大到小排序后的学生信息:\n");
for (i = 0; i < 10; i++) {
printf("%s %d\n", students[i].name, students[i].score);
}
return 0;
}
```
在这个程序中,我们使用了选择排序算法,逐步找到数组中最大元素的下标,然后将其移动到正确的位置。最后,按顺序输出排序后的学生信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)