所属年份:2011.3;2011.9;
已知学生的记录由学号和学习成绩构成,N名学生的数据已存入a结构体数组中。请编写函数fun,该函数的功能是:找出成绩最低的学生记录,通过形参返回主函数(规定只有一个最低分)。已给出函数的首部,请完成该函数。
#include<stdio.h> #include<string.h> #include<conio.h> #include<stdlib.h> #define N 10 typedef struct ss { char num[10]; int s; } STU; fun(STU a[], STU *s) { } void main() { FILE *wf; STU a[N]={{ "A01",81},{ "A02",89},{ "A03",66},{ "A04",87},{ "A05",77}, { "A06",90},{ "A07",79},{ "A08",61},{ "A09",80},{ "A10",71}},m; int i; system("CLS"); printf("*****The original data*****\n"); for(i=0;i<N;i++) printf("No=%s Mark=%d\n", a[i].num,a[i].s); fun(a,&m); printf("*****THE RESULT*****\n"); printf("The lowest :%s, %d\n",m.num,m.s); /******************************/ wf=fopen("out.dat","w"); fprintf(wf,"%s, %d",m.num,m.s); fclose(wf); /*****************************/ }
【解题思路】
找出结构体数组元素中的最小值。先认为第1个值最小,即*s=a[0];,如果在循环的过程中发现比第1个值更小的,就将指针s指向该元素,直到找到最小元素。另外,本题还涉及结构体中的指向运算符,请考生注意。
【参考答案】
fun(STU a[], STU *s) { int i; *s=a[0]; /*先认为第1个值最小*/ for(i=0;i<N;i++) /*如果在循环的过程中再发现比第1个值更小的则赋给*s*/ if(s->s>a[i].s) *s=a[i]; }