4.编写程序,输入n个学生的学号和成绩(有1位小数),按成绩从高到低排序输出,n 小于50,学号小于10位。C语言
时间: 2023-12-20 12:03:59 浏览: 71
用C语言编写的学生成绩系统程序
以下是一个简单的实现,使用结构体存储学生信息,使用冒泡排序按成绩从高到低排序:
```c
#include <stdio.h>
#define MAX_N 50
#define MAX_ID_LEN 10
typedef struct {
char id[MAX_ID_LEN];
float score;
} Student;
void swap(Student *a, Student *b) {
Student temp = *a;
*a = *b;
*b = temp;
}
void bubble_sort(Student students[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (students[j].score < students[j + 1].score) {
swap(&students[j], &students[j + 1]);
}
}
}
}
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
Student students[MAX_N];
for (int i = 0; i < n; i++) {
printf("Enter student %d's id and score: ", i + 1);
scanf("%s %f", students[i].id, &students[i].score);
}
bubble_sort(students, n);
printf("Sorted by score:\n");
for (int i = 0; i < n; i++) {
printf("%s %.1f\n", students[i].id, students[i].score);
}
return 0;
}
```
注意,此程序没有对输入的学号进行长度限制,如果需要可以在输入时进行判断。
阅读全文