首页 > 代码库 > 结构体指针排序
结构体指针排序
输入不超过30名学生的信息,包括姓名,单科分数,出生年月,对其排序后输出。
运用知识点:结构体、指针、排序、函数。
1 #include<stdio.h> 2 #include<string.h> 3 4 struct birth 5 { 6 int y; 7 int m; 8 int d; 9 }; 10 struct student 11 { 12 int num; 13 char name[20]; 14 double score; 15 struct birth birthday; 16 }; 17 18 19 int main() 20 21 { 22 struct student STU[30],*p; 23 p=STU; 24 void name_sort(struct student *p,int n); 25 void age_sort(struct student *p,int n); 26 void score_sort(struct student *p,int n); 27 int i; 28 printf("请分别输入学生的学号、姓名、一门成绩和出生年月日(输入分数小于0或大于100结束):\n"); 29 for(i=0;i<30;i++) 30 { 31 scanf("%d%s%lf%d%d%d",&(p+i)->num,(p+i)->name,&(p+i)->score,&(p+i)->birthday.y,&(p+i)->birthday.m,&(p+i)->birthday.d); 32 if((p+i)->score>100 || (p+i)->score<0) break; 33 } 34 int n=i; 35 36 printf("\n按照姓名排序:\n"); 37 name_sort(p,n); 38 printf("学号\t\t名字\t\t分数\t年\t月\t日\n"); 39 for(i=0;i<n;i++) 40 { 41 printf("%d\t\t%s\t\t%.2lf\t%d\t%d\t%d\t\n",(p+i)->num,(p+i)->name,(p+i)->score,(p+i)->birthday.y,(p+i)->birthday.m,(p+i)->birthday.d); 42 } 43 44 printf("\n按照分数从大到小排序:\n"); 45 printf("学号\t\t名字\t\t分数\t年\t月\t日\n"); 46 score_sort(p,n); 47 for(i=n;i>=0;i--) 48 { 49 printf("%d\t\t%s\t\t%.2lf\t%d\t%d\t%d\t\n",(p+i)->num,(p+i)->name,(p+i)->score,(p+i)->birthday.y,(p+i)->birthday.m,(p+i)->birthday.d); 50 } 51 52 printf("\n按照年龄从大到小排序:\n"); 53 printf("学号\t\t名字\t\t分数\t年\t月\t日\n"); 54 age_sort(p,n); 55 for(i=0;i<n;i++) 56 { 57 printf("%d\t\t%s\t\t%.2lf\t%d\t%d\t%d\t\n",(p+i)->num,(p+i)->name,(p+i)->score,(p+i)->birthday.y,(p+i)->birthday.m,(p+i)->birthday.d); 58 } 59 60 61 return 0; 62 } 63 void name_sort(struct student *p,int n)//姓名排序 64 { 65 int i, j; 66 struct student temp; 67 for (i = 0; i < n - 1; i++) 68 for (j = 0; j < n - 1 - i; j++) 69 if (strcmp((p + j)->name, (p + j + 1)->name) > 0){ 70 temp = *(p + j); 71 *(p + j) = *(p + j + 1); 72 *(p + j + 1) = temp;} 73 return; 74 return; 75 } 76 void age_sort(struct student *p,int n)//年龄排序 77 { 78 int i, j, b1, b2; 79 struct student temp; 80 for (i = 0; i<n - 1; i++) 81 for (j = 0; j < n - 1 - i; j++) 82 { 83 b1 = (p + j)->birthday.y * 10000 + (p + j)->birthday.m * 100 + (p + j)->birthday.d; 84 b2 = (p + j + 1)->birthday.y * 10000 + (p + j + 1)->birthday.m * 100 + (p + j + 1)->birthday.d; 85 if (b1 > b2)temp = *(p + j), *(p + j) = *(p + j + 1), *(p + j + 1) = temp; 86 } 87 return; 88 } 89 void score_sort(struct student *p, int n){ //分数排序 90 int i, j; 91 struct student temp; 92 for(i=0;i<n-1;i++) 93 for(j=0;j<n-1-i;j++){ 94 if((p+j)->score>(p+j+1)->score){ 95 temp = *(p + j); 96 *(p + j) = *(p + j + 1); 97 *(p + j + 1) = temp; 98 } 99 } 100 }
结构体指针排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。