结构体成绩排名,c语言编程
时间: 2023-11-02 15:17:43 浏览: 83
可以使用结构体数组来实现成绩排名。
首先,定义一个包含学生信息的结构体,例如:
```c
struct student {
char name[20];
int score;
};
```
然后,定义一个结构体数组来存储所有学生的信息,例如:
```c
struct student stu[100];
```
接下来,从用户输入中获取每个学生的姓名和成绩,并将其存储到结构体数组中。可以使用循环语句来实现:
```c
int n; // n表示学生总数
for (int i = 0; i < n; i++) {
printf("请输入第%d个学生的姓名和成绩:", i + 1);
scanf("%s %d", stu[i].name, &stu[i].score);
}
```
接着,根据成绩进行排序。可以使用冒泡排序或选择排序来实现。这里以冒泡排序为例:
```c
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (stu[j].score < stu[j + 1].score) {
struct student temp = stu[j];
stu[j] = stu[j + 1];
stu[j + 1] = temp;
}
}
}
```
最后,输出排名结果:
```c
printf("排名结果如下:\n");
for (int i = 0; i < n; i++) {
printf("第%d名:%s,成绩为%d\n", i + 1, stu[i].name, stu[i].score);
}
```
完整代码示例:
```c
#include <stdio.h>
struct student {
char name[20];
int score;
};
int main() {
struct student stu[100];
int n;
printf("请输入学生总数:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第%d个学生的姓名和成绩:", i + 1);
scanf("%s %d", stu[i].name, &stu[i].score);
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (stu[j].score < stu[j + 1].score) {
struct student temp = stu[j];
stu[j] = stu[j + 1];
stu[j + 1] = temp;
}
}
}
printf("排名结果如下:\n");
for (int i = 0; i < n; i++) {
printf("第%d名:%s,成绩为%d\n", i + 1, stu[i].name, stu[i].score);
}
return 0;
}
```