学生的记录由学号和成绩组成 N名学生的数据已存放在主函数的结构体数组s中 请编写函数fun 它的功
学生的记录由学号和成绩组成,N名学生的数据已存放在主函数的结构体数组s中,请编写函数fun,它的功能是:把低于平均分的学生数据放在b所指的数组中,低于平均分的学生人数通过形参n传回,平均分通过函数值返回。
[注意] 部分源程序给出如下。
请勿改动主函数main和其他函数中的任何内容,仅在fun函数的花括号中填入所编写的若干语句。
[试题源程序]
include<stdio.h>
define N 8
typedef struct
{
char num[10];
double s;
}STREC;
double fun(STREC *a, STREC *b, int *n)
{
}
void main()
{
STREC s[N]={{"GA05", 85},
{"GA03", 76}, {"GA02", 69}, {"GA04", 85},
{"GA01", 91}, {"GA07", 72}, {"GA08", 64},
{"GA06", 87}};
STREC h[N], t; FILE *out;
int i, j, n;
double ave;
ave=fun(s, h, &n);
printf("The %d student data which is lower than %7.3 f: ", n, ave);
for(i=0; i<n; i++)
printf("%s %4.1f ", h[i]. num, h[i].s);
printf(" ");
ut=fopen("out.dat", "W");
fprintf(out, "%d %7.3f ", n, ave);
for(i=0; 2<n-1; i++)
for(j=i+1; j<n; j++)
if(h[i]. s>h[j].s)
{
t=h[i];
h[i]=h[j];
h[j]=t;
}
for(i=0; 2<n; i++)
fprintf(out, "%4.1f ", h[i].s);
fclose(out);
}
请帮忙给出正确答案和分析,谢谢!
-
正确答案:int fun(STREC *a STREC *b int *n) { double ave=0.0; int i j=0; *n=0; for(i=0; i<N; i++) ave+=a[i].s; ave/=N; for(i=0; i<N; i++) if(a[i]. s<ave) { b[j]=a[i]; (*n)++; j++; } return ave; }
int fun(STREC *a, STREC *b, int *n) { double ave=0.0; int i, j=0; *n=0; for(i=0; i<N; i++) ave+=a[i].s; ave/=N; for(i=0; i<N; i++) if(a[i]. s<ave) { b[j]=a[i]; (*n)++; j++; } return ave; } 解析:本题的设计思路是:(1)定义两个变量,分别用于保存总分和平均值,定义循环变量并赋初值:(2)利用循环语句遍历所有学生的分数,累加求和并计算初值;(3)再次遍历结构体数组,找出低于平均分的分数,把该学生的记录保存在形参数组b中,并记录其个数;(4)用return语句返回平均值。
