#include<stdio.h> #include<malloc.h> #define LEN sizeof(struct student) #define M 3 #define k 5 struct student {long num; char name[30]; float score[4]; struct student *next; };
int n; //建立学生信息的链表 struct student *creat(void) {struct student *head; struct student *p1,*p2; int i; n=0; p1=p2=(struct student *)malloc(LEN); printf("请输入学生数据(输入'0'结束)\n"); printf("学号:");scanf("%ld",&p1->num);if(p1->num == 0) goto end; printf("姓名:");scanf("%s",&p1->name); for(i=1;i<4;i++) {printf("成绩[%d]=",i);scanf("%f",&p1->score[i]);} head=NULL; while(p1->num!=0) {n=n+1; if(n==1)head=p1; else p2->next=p1; p2=p1; p1=(struct student *)malloc(LEN); printf("学号:");scanf("%ld",&p1->num); printf("姓名:");scanf("%s",&p1->name); for(i=1;i<4;i++) {printf("成绩[%d]=",i);scanf("%f",&p1->score[i]);} } p2->next=NULL; end:return(head); } //输出所有学生的信息 int print(struct student *head) {struct student *p; int i; printf("\n现在有 %d 个学生的数据,如下:\n",n); p=head; if(head!=NULL) do {printf(" 学号 %ld 姓名 %s\n",p->num,p->name); for(i=1;i<4;i++) printf("成绩[%d]=%5.2f\n",i,p->score[i]); p=p->next; }while(p!=NULL); return (n); }
//求所有学生n门课和的总平均成绩 float average(int M,struct student *head) {struct student *p; float aver[M]; float sum,aver_all=0; int i; p=head; while(M != 0) { for(i=1;i<=M;i++) { for(j=1;j<=k;j++) {aver[i]=p->score[i];p=p->next;} aver[i]=aver[i]/k;}m--;}; for(i=1;i<M;i++) aver_all+=(aver[i]+aver[i+1]); aver_all=aver_all/M; for(i=1;i<=M;i++) return(aver[i]); return(aver_all); }
main() { struct student *head; head=creat(); print(head); printf("所有学生%d门课的平均成绩为:%5.2f\n",M,average(head,M)); }