义一个包含5个教师成员的结构体数组,教师信息包括职工号、姓名和工资。要求从键盘输入所有教师的信息,并设计一个sort函数实现结构体数组按教师工资由少到多排序。目前,已编辑完成main函数,请编程实现input函数、output函数和sort函数,分别实现教师信息的录入、输出与排序。
时间: 2023-06-13 09:08:37 浏览: 176
下面是完整的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TEACHERS 5
struct Teacher {
int id;
char name[20];
float salary;
};
void input(struct Teacher *teachers, int count) {
printf("请输入%d名教师的信息:\n", count);
for (int i = 0; i < count; i++) {
printf("请输入第%d名教师的职工号:", i + 1);
scanf("%d", &teachers[i].id);
printf("请输入第%d名教师的姓名:", i + 1);
scanf("%s", teachers[i].name);
printf("请输入第%d名教师的工资:", i + 1);
scanf("%f", &teachers[i].salary);
}
}
void output(struct Teacher *teachers, int count) {
printf("所有教师的信息如下:\n");
for (int i = 0; i < count; i++) {
printf("职工号:%d\t姓名:%s\t工资:%.2f\n", teachers[i].id, teachers[i].name, teachers[i].salary);
}
}
int compare_by_salary(const void *a, const void *b) {
const struct Teacher *ta = (const struct Teacher *)a;
const struct Teacher *tb = (const struct Teacher *)b;
if (ta->salary < tb->salary) {
return -1;
} else if (ta->salary > tb->salary) {
return 1;
} else {
return 0;
}
}
void sort(struct Teacher *teachers, int count) {
qsort(teachers, count, sizeof(struct Teacher), compare_by_salary);
}
int main() {
struct Teacher teachers[MAX_TEACHERS];
input(teachers, MAX_TEACHERS);
sort(teachers, MAX_TEACHERS);
output(teachers, MAX_TEACHERS);
return 0;
}
```
首先,在结构体定义中,我们定义了包含职工号、姓名和工资信息的教师结构体。然后,我们定义了三个函数:input函数用于从键盘输入所有教师的信息,output函数用于输出所有教师的信息,sort函数用于按照教师工资由少到多排序。
在input函数中,我们通过for循环遍历所有教师,使用scanf函数从键盘输入职工号、姓名和工资信息,分别保存到结构体中。
在output函数中,我们同样使用for循环遍历所有教师,使用printf函数输出职工号、姓名和工资信息。
在sort函数中,我们使用了C标准库中的qsort函数,它可以根据我们指定的比较函数,对结构体数组进行排序。我们定义了一个compare_by_salary函数,用于按照教师工资大小比较两个教师结构体的大小。最后,在main函数中,我们先调用input函数输入所有教师的信息,然后调用sort函数按照教师工资大小排序,最后调用output函数输出所有教师的信息。
注意,在程序中,我们使用了宏定义MAX_TEACHERS来表示教师数组的最大长度,这样可以方便地修改教师数组的长度。