c语言编写程序,输入n个学生的学号和成绩(有1位小数),按成绩从高到低排序输出,n 小于50,学号小于10位。 运用结构体
时间: 2023-06-24 15:03:02 浏览: 56
下面是一个实现这个功能的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_N 50
#define MAX_ID_LEN 10
typedef struct {
char id[MAX_ID_LEN + 1];
double score;
} Student;
int compare(const void *a, const void *b)
{
const Student *s1 = (const Student *)a;
const Student *s2 = (const Student *)b;
if (s1->score < s2->score) {
return 1;
} else if (s1->score > s2->score) {
return -1;
} else {
return 0;
}
}
int main()
{
int n;
Student students[MAX_N] = {0};
printf("请输入学生数n:");
scanf("%d", &n);
if (n > MAX_N) {
printf("学生数不能超过%d\n", MAX_N);
return 1;
}
printf("请输入学生的学号和成绩,每行一个,中间用空格隔开:\n");
for (int i = 0; i < n; i++) {
scanf("%s %lf", students[i].id, &students[i].score);
}
qsort(students, n, sizeof(Student), compare);
printf("按成绩从高到低排序的结果为:\n");
for (int i = 0; i < n; i++) {
printf("%s %.1lf\n", students[i].id, students[i].score);
}
return 0;
}
```
程序中使用了一个结构体 `Student`,其中包含学生的学号和成绩两个属性。通过 `compare` 函数实现从高到低排序。程序中使用了标准库函数 `qsort` 进行排序,最后按照排序结果输出学号和成绩。