標籤:
eg:9.7 有n個結構體變數,內含學生學號,姓名和3門課成績,要求輸出平均成績最高的學生的資訊(內含學生學號,姓名和3門課成績和平均成績)。
2015-01-2022:25:34
1 #include<stdio.h> 2 #define N 2 3 4 struct Student 5 { 6 int num; 7 char name[20]; 8 float score[3]; 9 float aver;10 };11 12 void input(struct Student *stu)13 {14 int i;15 printf("input the student‘s information:\nname,num,three score\n");16 for(i=0;i<N;i++,stu++)17 {18 scanf("%s %d %f %f %f",stu->name,&stu->num ,19 &stu->score[0],&stu->score[1],&stu->score[2]);20 stu->aver=(stu->score[0]+stu->score[1]+stu->score[2])/3;21 }22 }23 24 struct Student *Max(struct Student *stu)25 {26 int i;27 int m=0;28 for(i=0;i<N;i++)29 {30 if(stu[i].aver>stu[m].aver)31 {32 m=i;33 }34 }35 return &stu[m];36 }37 38 void print_stu(struct Student *stud)39 {40 printf("\nThe average scores of the top students is:\n");41 printf("num:%d\nname:%s\nthe three subject:%5.1f,%5.1f,%5.1f\nthe aver score:%6.2f\n",stud->num,stud->name,stud->score[0],stud->score[1],stud->score[2],stud->aver); 42 }43 44 int main()45 {46 struct Student stu[N];47 struct Student *p = stu;48 input(p);49 print_stu(Max(p));50 return 0;51 }
譚浩強C程式設計(第四版)例題中的代碼最佳化