C語言,有5名學生儲存在結構體陣列中,程式設計按學生的成績升序排序,按學生的姓名降序排序,按年齡從低到高排序
阿新 • • 發佈:2018-12-25
有5名學生儲存在結構體陣列中,程式設計按學生的成績升序排序,按學生的姓名降序排序,按年齡從低到高排序
//我把宣告檔案放在.h檔案中
//把函式實現部分放在.m檔案中
//最後的函式呼叫放在主函式main中,程式碼如下
.h檔案
.m檔案typedef struct student{ char name[10]; //儲存學生姓名 float score; //儲存學生成績 int age; //儲存學生年齡 }Stud; //輸出結構體成員 void outputStudent(Stud stu); //輸出所有成員的資訊 void outputAllStudent(Stud b[], int count);
//輸出結構體成員
void outputStudent(Stud stu){
printf("Name = %s Score = %.2f Age = %d", stu.name, stu.score, stu.age);
}
//輸出所有學生的資訊
void outputAllStudent(Stud b[], int count){
for (int i = 0; i < count; i++) {
printf("\n");
outputStudent(b[i]);
}
}
主函式main內
//1.有5名學生儲存在結構體陣列中,程式設計按學生的成績升序排序,按學生的姓名降序排序,按年齡從低到高排序 Stud a[5] ={ {"oubama", 59.9, 44}, {"xilayi", 76.0, 55}, {"baideng",49.01, 50}, {"bushen",71.9, 66}, {"kelindun",83.3, 33}, }; //輸出所有學生結構體成員 printf("輸出前:"); outputAllStudent(a, 5); printf("\n"); //1)程式設計按學生的成績升序排序 printf("成績生序排序後為:"); for (int i = 0; i < 5 - 1; i++) { for (int j = 0; j < 5 - 1 - j; j++) { if (a[j].score > a[j + 1].score) { Stud tempStud = {0}; tempStud = a[j]; a[j] = a[j + 1]; a[j + 1] = tempStud; } } } outputAllStudent(a, 5); //2)按學生的姓名降序排序 printf("\n按學生姓名排序後:"); for (int i = 0; i < 5 - 1; i++) { for (int j = 0; j < 5 - 1 - i; j++) { if (strcmp(a[j].name, a[j + 1].name) < 0) { Stud tempStud = {0}; tempStud = a[j]; a[j] = a[j + 1]; a[j + 1] = tempStud; } } } outputAllStudent(a, 5); //2)按年齡從低到高排序 printf("\n按年齡從低到高排序後:"); for (int i = 0; i < 5 - 1; i++) { for (int j = 0; j < 5 - 1 - i; j++) { if (a[j].age > a[j + 1].age) { Stud tempStud = {0}; tempStud = a[j]; a[j] = a[j + 1]; a[j + 1] = tempStud; } } } outputAllStudent(a, 5);