2.通过函数调用实现:讲结构体数组中的三个元素按num成员进行升序排列。
要求:
①数组元素依次赋初值为:{12,"sunny",89.1}、{8,"henry",73.5}、{21,"lucy",91.7}。
②结构体定义如下:struct s{int num;char name[30];float score;};
#include<stdio.h> struct s{ int num; char name[30]; float score; }a[3] = {{12,"sunny",89.1} , {8,"henry",73.5} , {21,"lucy",91.7}}; void fun() { int i,j; struct s t; for(i=0; i<2; i++) { for(j=0; j<2-i; j++) { if(a[j].num > a[j+1].num) { t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } } } int main() { int i; fun(); for(i=0; i<3; i++) { printf("%d,%s,%f\n",a[i].num , a[i].name , a[i].score); } return 0; }
8,henry,73.500000
12,sunny,89.099998
21,lucy,91.699997
#include<stdio.h> struct s{ int num; char name[30]; float score; }; void fun(struct s *a , int n) { int i,j; struct s t; for(i=0; i<n-1; i++) { for(j=0; j<n-1-i; j++) { if(a[j].num > a[j+1].num) { t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } } } int main() { struct s a[3] = {{12,"sunny",89.1} , {8,"henry",73.5} , {21,"lucy",91.7}}; int i; fun(a,3); for(i=0; i<3; i++) { printf("%d,%s,%f\n",a[i].num , a[i].name , a[i].score); } return 0; }
8,henry,73.500000
12,sunny,89.099998
21,lucy,91.699997