一维数组实验题:班级共有 m个人,该班C语言的成绩存放在score(score为整数)数组中,计算该班成绩的平均分,并将小于平均分的成绩存储在一个数组中,并打印该数组的值。
要求:
- 请编写函数fun, 它的功能是:计算平均分,并将低于平均分的成绩和相应的数组下标分别存在不同的数组中(打印语句放在主函数中),声明如下:
int fun(int score[], int m, int below_score[], int below_index[]); - 请编写函数ReadScore,读入成绩,返回输入的有效人数,声明如下:
int ReadScore(int score[]); - 需要对数组越界做判断,如:在输入时,直接输入-1的情况,此时显示“there are no valid scores”,并终止程序。
- 班机最多有40人,用宏定义数组的所含最多的元素数量。
输入:每一行输入一个人的成绩,直到输入值为负数时,结束成绩的输入,并将此时拥有的成绩数量,作为班级人数,
输出:打印班级的总人数,低于平均分的,低于平均分的成绩及该成绩在输入时的序号,从1开始计数,
输入格式:scanf("%d", &score[i]);
输出提示:
if (n == 0) //1
{
printf(“there are no valid scores\n”);
exit(0);
}
printf(“the number of the class:%d\n”, n);
printf(“the number under the average score: %d\n”, below_n);
for (i = 0; i < below_n; i++)
{
printf(“the %dth score is: %d\n”, below_index[i] + 1, below_score[i]); //1
}
程序运行示例:
45
67
98
-1
the number of the class:3
the number under the average score: 2
the 1th score is: 45
the 2th score is: 67
#include<stdio.h>
#include<stdlib.h>
#define MAX 40 //最大人数
int fun(int score[], int m, int below_score[], int below_index[]);//计算平均分,并将低于平均分的成绩和相应的数组下标分别存在不同的数组中
int ReadScore(int score[]);//读入成绩,返回输入的有效人数
int main()
{
int score[MAX],i,below_score[MAX],below_index[MAX],m,n;
m=ReadScore(score);
n=fun(score,m,below_score,below_index);
printf("the number of the class:%d\n", m);
printf("the number under the average score: %d\n",n);
for (i=0;i<n;i++)
{
printf("the %dth score is: %d\n",below_index[i]+1,below_score[i]);
}
return 0;
}
int ReadScore(int score[])
{
int i,t=0;
for(i=0;i<MAX;i++)
{
scanf("%d", &score[i]);
if(score[0]==-1)
{
printf("there are no valid scores\n");
exit(0);
}
t++;
if(score[i]==-1)
{
t--;
break;
}
}
return t;
}
int fun(int score[], int m, int below_score[], int below_index[])
{
int i,s=0,k,t=0;
float a;
for(i=0;i<m;i++)
{
s+=score[i];
}
a=(float)s/m;
for(k=0;k<m;k++)
{
if(score[k]<a)
{
below_score[t]=score[k];
below_index[t]=k;
t++;
}
}
return t;
}