例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語言輸出平均成績最高學生的資訊
更多案例可以go公眾號:C語言入門到精通
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/239138.html
標籤:其他
上一篇:不對外開放的微信小程式審核時不通過,因為無法提供測驗賬號導致審核人員登錄失敗解決辦法!
下一篇:AnyLogic中的代碼補全
