1. 程式人生 > 實用技巧 >C語言 | 輸出平均成績最高學生的資訊

C語言 | 輸出平均成績最高學生的資訊

例41:有n個結構體變數,內含學生的學號,學號,和三門成績。要求輸出平均成績最高學生的資訊(包括學號、姓名、三門課程成績和平均成績)


解題思路:將n個學生的資料表示為結構體陣列(有n個元素)。按照功能函式化的思想,小林分別用3個函式來實現不同的功能。
原始碼演示:

#include<stdio.h>//標頭檔案
#define N 3//巨集定義
struct student //學生類結構體
{
  int num; //學號
  char name[20];//姓名
  float score[3];//成績
  float aver;//平均分
} ;
int main() //主函式
{
  void input(struct
student s[]);//函式宣告 struct student max(struct student s[]);//函式宣告 void print(struct student s);//函式宣告 struct student s[N],*p=s;//定義結構體變數 input (p);//呼叫函式 print(max(p));//列印呼叫max函式結果 return 0;//主函式返回值為0 } void input(struct student s[])//自定義輸入函式 { int i;//定義整型變數 printf("請輸入各學生的資訊:學號、姓名、三門課成績:\n");//提示語句
for(i=0;i<N;i++)//迴圈N次 { scanf("%d %s %f %f %f",&s[i].num,&s[i].name,&s[i].score[0],&s[i].score[1],&s[i].score[2]);//輸入資訊 s[i].aver=(s[i].score[0]+s[i].score[1]+s[i].score[2])/3;//求平均值 } } struct student max(struct student s[])//自定義求最大值 { int i,m=0;//定義整型變數 for(i=0
;i<N;i++)//迴圈N次 { if(s[i].aver>s[m].aver)//把平均分大的i賦值給m { m=i; } } return s[m];//將s[m]結果返回到函式呼叫處 } void print (struct student stud)//自定義列印函式 { printf("\n成績最高的學生是:\n");//提示語句 printf("學號;%d\n姓名;%s\n三門課成績:%5.1f,%5.1f,%5.1f\n平均成績:%6.2f\n", stud.num,stud.name,stud.score[0],stud.score[1],stud.score[2],stud.aver);//輸出結果 }

編譯執行結果如下:

請輸入各學生的資訊:學號、姓名、三門課成績:
10010 Tom 100 90 80
10011 Jon 80 70 100
10012 Kim 100 90 95

成績最高的學生是:
學號;10012
姓名;Kim
三門課成績:100.0, 90.0, 95.0
平均成績: 95.00

--------------------------------
Process exited after 44.45 seconds with return value 0
請按任意鍵繼續. . .

C語言學習路線

C語言開發工具

C語言|輸出平均成績最高學生的資訊