自定义数据类型
【问题:选出高于平均成绩的学生名单】
学生的记录由学号和成绩组成。N名学生的数据已放入主函数中的结构体数组s中,请编写函数fun,其功能是:把高于等于平均分的学生数据放在b所指的数组中,高于等于平均分的学生人数通过形参n传回,平均分通过函数值返回。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <stdio.h> #define N 12 typedef struct { char num[10]; double score; } Student; double fun( Student a[], Student b[], int *n ) { int i, j=0; double av=0.0; for(i=0; i<N; i++) av=av+a[i].score; av=av/N; for(i=0; i<N; i++) if (a[i].score>av) b[j++]=a[i]; *n = j; return av; } int main(int argc, char *argv[]) { Student s[N]= {{"GA05",85},{"GA03",76},{"GA02",69},{"GA04",85}, {"GA01",91},{"GA07",72},{"GA08",64},{"GA06",87}, {"GA09",60},{"GA11",79},{"GA12",73},{"GA10",90} }; Student h[N], t; int i, n; double ave; ave=fun(s, h, &n); printf("The %d student data which is higher than %7.3f:\n",n,ave); for(i=0; i<n; i++) printf("%s %4.1f\n",h[i].num,h[i].score); return 0; } |
程序的运行结果如下:
1 2 3 4 5 6 7 | The 6 student data which is higher than 77.583: GA05 85.0 GA04 85.0 GA01 91.0 GA06 87.0 GA11 79.0 GA10 90.0 |
【问题】
N名学生的成绩已在主函数中放入一个带头节点的链表结构中,h指向链表的头节点。请编写函数fun,其功能是:求出平均分,并由函数值返回。
例如,若学生的成绩是:85 76 69 85 91 72 64 87,则平均分应当是:78.625。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include <stdio.h> #include <stdlib.h> #define N 8 struct slist { double s; struct slist *next; }; typedef struct slist STREC; double fun( STREC *h ) { double ave=0.0; STREC *p; for (p=h->next; p!=NULL; p=p->next) ave=ave + p->s; return ave/N; } STREC* creat( double *s) { STREC *h,*p,*q; int i; h=p=(STREC*)malloc(sizeof(STREC)); p->s=0; for (i=0; i<N; i++) { q=(STREC*)malloc(sizeof(STREC)); q->s=s[i]; p->next=q; p=q; } p->next=0; return h; } void outlist( STREC *h) { STREC *p; p=h->next; printf("head"); do { printf("->%4.1f",p->s); p=p->next; } while(p!=0); printf("\n"); } int main(int argc, char *argv[]) { double s[N]= {85,76,69,85,91,72,64,87},ave; STREC *h; h=creat(s); outlist(h); ave=fun(h); printf("ave= %6.3f\n",ave); return 0; } |
1 |
1 |