在C语言中定义结构体,成员包括姓名和成绩,在主函数中定义结构体数组(含有五个元素)键盘赋值,对姓名成员进行降序排序,输出排序后的数组(两个成员都输出)
时间: 2024-03-25 07:38:37 浏览: 18
好的,代码如下:
```c
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int score;
};
void sort(struct Student arr[], int n) {
int i, j;
struct Student temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (strcmp(arr[i].name, arr[j].name) < 0) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int main() {
struct Student students[5];
int i;
for (i = 0; i < 5; i++) {
printf("请输入第%d个学生的姓名和成绩:", i + 1);
scanf("%s%d", students[i].name, &students[i].score);
}
sort(students, 5);
printf("排序后的数组:\n");
for (i = 0; i < 5; i++) {
printf("%s %d\n", students[i].name, students[i].score);
}
return 0;
}
```
在上面的代码中,首先定义了一个结构体 `Student`,其中包含两个成员,分别是姓名和成绩。在 `main` 函数中,定义了一个 `Student` 类型的数组 `students`,并通过键盘输入为其赋值。然后调用 `sort` 函数对数组进行降序排序,最后按照要求输出排序后的数组。在 `sort` 函数中,通过 `strcmp` 函数比较姓名的大小,实现了对姓名成员的降序排序。