项目:创建一个公司员工的结构体,储存员工的姓名、工龄、年龄。
要求:在主函数里创建5个结构体数组,从终端输入信息,分别以工龄排序和年龄排序输出,排序方式自定。
代码如下:
#include <iostream>
#include<string.h>
#include<stdio.h>
//创建员工信息的结构体
struct Staff
{
char name[20];
int seniority;
int age;
};
//录入员工信息
void scanfStaInf(struct Staff* information)
{
printf("请输入员工姓名:");
scanf("%s", information->name);
printf("请输入员工工龄:");
scanf("%d", &information->seniority);
printf("请输入员工年龄:");
scanf("%d",&information->age);
printf("---------------\n");
}
//循环录入
void scanfStaInf1(struct Staff* array,int elength)
{
for (int i = 0; i < elength; i++)
{
scanfStaInf(&array[i]);//调用录入员工信息的函数
}
}
//比较年龄,由小到大
int compareAge(struct Staff*p1, struct Staff*p2)
{
if (p1->age == p2->age)
{
if (p1->seniority > p2->seniority)
{
return p1->seniority > p2->seniority;
}
}
return p1->age > p2->age;
}
//比较工龄,由小到大
int compareSeniority(struct Staff* p1, struct Staff* p2)
{
if (p1->seniority == p2->seniority)
{
if (p1->age>p2->age)
{
return p1->age > p2->age;
}
}
return p1->seniority >p2->seniority;
}
//使用冒泡排序
void orderBySta(struct Staff* arry, int elength, int (*compareSeniority)(struct Staff* p1, struct Staff* p2))
{
for (int i = 0; i < elength-1; i++)
{
for (int j = 0; j < elength-1-i; j++)
{
if (compareSeniority(&arry[j],&arry[j+1]))
{
struct Staff temp = arry[j];
arry[j] = arry[j + 1];
arry[j + 1] = temp;
}
}
}
}
//打印信息
void printStaInf(struct Staff Print)
{
printf("name:%s seniority:%d age:%d\n", Print.name, Print.seniority, Print.age);
}
//循环数组
void circulation(struct Staff* Print,int length)
{
for (int i = 0; i < length; i++)
{
printStaInf(Print[i]);//调用打印信息的函数
}
printf("----------------\n");
}
int main()
{
//创建5个结构体数组
struct Staff Information[5];
//录入员工信息
scanfStaInf1(Information, 5);
//调用排序,按工龄排序,工龄相同,则看年龄
orderBySta(Information, 5, compareSeniority);
//读取员工信息
circulation(Information,5);
//调用排序,按年龄排序,年龄相同,看工龄
orderBySta(Information, 5, compareAge);
//读取员工信息
circulation(Information, 5);
}
`