簡單結構體練習
阿新 • • 發佈:2018-11-20
專案:建立一個公司員工的結構體,儲存員工的姓名、工齡、年齡。
要求:在主函式裡建立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);
}
`