定义一个包含5个教师成员的结构体数组,教师信息包括职工号、姓名和工资。要求从键盘输入所有教师的信息,并设计一个sort函数实现结构体数组按教师工资由少到多排序。目前,已编辑完成main函数,请编程实现
时间: 2024-06-07 16:10:21 浏览: 66
以下是实现代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 5
struct Teacher {
char id[20];
char name[20];
int salary;
};
int cmp(const void *a, const void *b) {
const struct Teacher *pa = (const struct Teacher *)a;
const struct Teacher *pb = (const struct Teacher *)b;
return pa->salary - pb->salary;
}
int main() {
struct Teacher teachers[MAX_NUM];
for (int i = 0; i < MAX_NUM; i++) {
printf("请输入第%d个教师的职工号、姓名、工资(用空格分隔):", i+1);
scanf("%s%s%d", teachers[i].id, teachers[i].name, &teachers[i].salary);
}
qsort(teachers, MAX_NUM, sizeof(struct Teacher), cmp);
printf("按工资由少到多排序的教师信息为:\n");
for (int i = 0; i < MAX_NUM; i++) {
printf("%s\t%s\t%d\n", teachers[i].id, teachers[i].name, teachers[i].salary);
}
return 0;
}
阅读全文