3.输入考生的学号、姓名、考试成绩。输入 5 个考 生信息,按照成绩大小升序和逆序输出。使用指针函数,函数调用和 结构体。
时间: 2023-05-24 11:06:42 浏览: 129
C++数组指针题(含答案).pdf
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char id[10];
char name[20];
int score;
} Student;
void ascending_sort(Student *students, int num);
void descending_sort(Student *students, int num);
void print_students(Student *students, int num);
int main() {
int num = 5;
Student students[num];
// 输入学生信息
for (int i = 0; i < num; i++) {
printf("请输入第%d个学生的学号:", i+1);
scanf("%s", students[i].id);
printf("请输入第%d个学生的姓名:", i+1);
scanf("%s", students[i].name);
printf("请输入第%d个学生的成绩:", i+1);
scanf("%d", &students[i].score);
}
// 按成绩升序排序并输出
ascending_sort(students, num);
printf("按成绩升序排序的结果如下:\n");
print_students(students, num);
// 按成绩降序排序并输出
descending_sort(students, num);
printf("按成绩降序排序的结果如下:\n");
print_students(students, num);
return 0;
}
// 成绩升序排序
void ascending_sort(Student *students, int num) {
Student temp;
for (int i = 0; i < num-1; i++) {
for (int j = 0; j < num-1-i; j++) {
if (students[j].score > students[j+1].score) {
temp = students[j];
students[j] = students[j+1];
students[j+1] = temp;
}
}
}
}
// 成绩降序排序
void descending_sort(Student *students, int num) {
Student temp;
for (int i = 0; i < num-1; i++) {
for (int j = 0; j < num-1-i; j++) {
if (students[j].score < students[j+1].score) {
temp = students[j];
students[j] = students[j+1];
students[j+1] = temp;
}
}
}
}
// 输出学生信息
void print_students(Student *students, int num) {
printf("学号\t姓名\t成绩\n");
for (int i = 0; i < num; i++) {
printf("%s\t%s\t%d\n", students[i].id, students[i].name, students[i].score);
}
}
阅读全文