3. 编程题

来源:百度知道 编辑:UC知道 时间:2024/06/07 20:14:56
3. 编程题
m个人的成绩存放在score数组中,请编写函数fun(),它的功能是:将低于平均分的人数作为函数值返回,将低于平均分的分数放在below所指的数组中。
例如,当score数组中的数据为10,20,30,40,50,60,70,80,90时,函数返回的人数应该是4,below中的数据应为10,20,30,40。
注意:部分源程序给出如下。
请勿改动主函数main和其他函数中的任何内容,仅在函数fun的花括号中填入所编写的若干语句。
试题程序:
#include <conio.h>
#include <stdio.h>
#include <string.h>
int fun(int score[],int m, int below[])
{

}
main()
{
int i, n, below[9];
int score[9]={10,20,30,40,50,60,70,80,90};
clrscr();
n=fun(score, 9, below);
printf("\nBelow the average score are: ");
for(i=0;i<n;i++)
printf("%d",below[i]);
}

我编的哪错了,麻烦看一下int fun(int score[],int m, int below[])
{int sum=0;float f;int i,j=0;
while(*score!='0')
{sum=sum+*score;score++;};f=sum/m;
for(i=0;i<m;i++)
{if(score[i]<f) below[j++]=score[i];
}

return (j);}

while(*score!='0')
{sum=sum+*score;score++;};
后面多;就不说了。这个地方是错的,虽然数组和指针在某种意义上是等价的,但数组名只能代表数组的首地址,其在程序运行期间是固定不变的是常量。
你可以改成这样:
int fun(int score[],int m, int below[])
{
int sum=0;
float f;
int i,j=0;
for(i=0;i<m;i++)
sum=sum+score[i];
f=(float)sum/m;
for(i=0;i<m;i++)
if(score[i]<f) below[j++]=score[i];
return (j);
}
你去试一下,我没有运行的。

while(*score!=\'0\')

这里你的结束标准不对,它是以 m 个数据为准的,而不是以是否为 0 而结束的。

f=sum/m;

这里虽然 f 是 float 类型,但是它也无法得到一个小数结果,因为 sum/m 的商永远只会得出一个整数值。你应该使用:f = ((double)sum) / m; 之类的方法。

其它好像没问题,我没有调试。

while(*score!='0') ?这个是什么
难道数组是以ascii码为48的'0'结束吗?
数组越界取得的可不一定是'\0'或是0或是其他什么固定的值;
还是用for吧:
for (i=0;i<m;i++,score++)
sum+=*score;

应该:
for(int i = 0; i < m; i++) // m代表成绩的数目。

不能while(*score!='0')
因为:
首先‘0’并不代表0。