用C语言编写几个函数,分别完成以下功能:输入5位职工的姓名和职工号;按职工号由小到大排序,姓名也随之排序;从键盘输入一个职工号,查找该职工的姓名。用主函数调用这些函数
时间: 2024-05-10 21:15:52 浏览: 69
以下是用C语言编写的几个函数,分别完成以上功能:
```c
#include <stdio.h>
#include <string.h>
// 定义最大职工数量
#define MAX_EMPLOYEES 5
// 职工结构体
typedef struct Employee {
char name[20]; // 姓名
int id; // 职工号
} Employee;
// 输入职工信息函数
void inputEmployeeInfo(Employee employees[]) {
printf("请输入%d位职工的姓名和职工号:\n", MAX_EMPLOYEES);
for (int i = 0; i < MAX_EMPLOYEES; i++) {
printf("请输入第%d位职工的姓名:", i + 1);
scanf("%s", employees[i].name);
printf("请输入第%d位职工的职工号:", i + 1);
scanf("%d", &employees[i].id);
}
}
// 排序函数
void sortEmployees(Employee employees[]) {
// 冒泡排序实现按职工号从小到大排序,姓名也随之排序
for (int i = 0; i < MAX_EMPLOYEES - 1; i++) {
for (int j = 0; j < MAX_EMPLOYEES - i - 1; j++) {
if (employees[j].id > employees[j + 1].id) {
// 交换职工号
int tempId = employees[j].id;
employees[j].id = employees[j + 1].id;
employees[j + 1].id = tempId;
// 交换姓名
char tempName[20];
strcpy(tempName, employees[j].name);
strcpy(employees[j].name, employees[j + 1].name);
strcpy(employees[j + 1].name, tempName);
}
}
}
}
// 查找职工姓名函数
void findEmployeeName(Employee employees[], int id) {
for (int i = 0; i < MAX_EMPLOYEES; i++) {
if (employees[i].id == id) {
printf("职工号为%d的职工姓名为%s\n", id, employees[i].name);
return;
}
}
printf("未找到职工号为%d的职工\n", id);
}
// 主函数
int main() {
Employee employees[MAX_EMPLOYEES];
inputEmployeeInfo(employees);
sortEmployees(employees);
printf("职工信息按职工号从小到大排序如下:\n");
for (int i = 0; i < MAX_EMPLOYEES; i++) {
printf("姓名:%s\t职工号:%d\n", employees[i].name, employees[i].id);
}
int id;
printf("请输入要查找的职工号:");
scanf("%d", &id);
findEmployeeName(employees, id);
return 0;
}
```
使用主函数调用这些函数:
```c
int main() {
Employee employees[MAX_EMPLOYEES];
inputEmployeeInfo(employees);
sortEmployees(employees);
printf("职工信息按职工号从小到大排序如下:\n");
for (int i = 0; i < MAX_EMPLOYEES; i++) {
printf("姓名:%s\t职工号:%d\n", employees[i].name, employees[i].id);
}
int id;
printf("请输入要查找的职工号:");
scanf("%d", &id);
findEmployeeName(employees, id);
return 0;
}
```
阅读全文