C语言编写一个函数,要求:1、要定义一个结构体类型,声明结构体变量staff数组 ;2、编程实现结构体数组(可以使用链表),将5名员工的数据输入计算机,并列表从屏幕输出并具有查询功能,3、编写函数,通过调用函数实现:按工作证号、姓名等查找员工的有关信息并在屏幕上输出
时间: 2024-03-17 17:45:52 浏览: 102
好的,以下是符合你要求的 C 代码实现:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STAFF_NUM 5 // 员工数量
// 员工结构体类型定义
typedef struct Staff {
char id[10]; // 工作证号
char name[20]; // 姓名
int age; // 年龄
float salary; // 工资
} Staff;
// 显示员工信息
void displayStaff(Staff staff[]) {
printf("工作证号\t姓名\t年龄\t工资\n");
for (int i = 0; i < MAX_STAFF_NUM; i++) {
printf("%s\t%s\t%d\t%.2f\n", staff[i].id, staff[i].name, staff[i].age, staff[i].salary);
}
}
// 按姓名查找员工信息
void searchStaffByName(Staff staff[], char name[]) {
printf("工作证号\t姓名\t年龄\t工资\n");
for (int i = 0; i < MAX_STAFF_NUM; i++) {
if (strcmp(staff[i].name, name) == 0) {
printf("%s\t%s\t%d\t%.2f\n", staff[i].id, staff[i].name, staff[i].age, staff[i].salary);
}
}
}
// 按工作证号查找员工信息
void searchStaffById(Staff staff[], char id[]) {
printf("工作证号\t姓名\t年龄\t工资\n");
for (int i = 0; i < MAX_STAFF_NUM; i++) {
if (strcmp(staff[i].id, id) == 0) {
printf("%s\t%s\t%d\t%.2f\n", staff[i].id, staff[i].name, staff[i].age, staff[i].salary);
}
}
}
int main() {
Staff staff[MAX_STAFF_NUM]; // 员工结构体数组定义
// 输入员工信息
for (int i = 0; i < MAX_STAFF_NUM; i++) {
printf("请输入第%d名员工信息:\n", i + 1);
printf("工作证号:");
scanf("%s", staff[i].id);
printf("姓名:");
scanf("%s", staff[i].name);
printf("年龄:");
scanf("%d", &staff[i].age);
printf("工资:");
scanf("%f", &staff[i].salary);
}
// 显示员工信息
displayStaff(staff);
// 按姓名查找员工信息
char name[20];
printf("请输入要查找的员工姓名:");
scanf("%s", name);
searchStaffByName(staff, name);
// 按工作证号查找员工信息
char id[10];
printf("请输入要查找的员工工作证号:");
scanf("%s", id);
searchStaffById(staff, id);
return 0;
}
```
首先定义了一个 `Staff` 结构体类型,包含 `id`、`name`、`age` 和 `salary` 四个成员变量,代表员工的工作证号、姓名、年龄和工资。
然后在 `main` 函数中定义了一个 `staff` 数组,用于存储 5 名员工的信息。先通过 `for` 循环输入员工信息,再通过调用 `displayStaff` 函数来显示员工信息。接着通过调用 `searchStaffByName` 和 `searchStaffById` 函数来按姓名和工作证号查找员工信息,并在屏幕上输出。
最后需要注意的是,为了防止结构体数组越界,我们在定义 `Staff` 结构体类型时,需要将数组大小的值定义成宏常量 `MAX_STAFF_NUM`,并在 `for` 循环中使用 `MAX_STAFF_NUM`,这样就可以保证不会越界了。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)