问题:为什么要使用数组?
如果我们读入两个学生的成绩并求其平均分, 那么只需要两个变量就可以轻松解决该问题. 那么如果读入100个学生的成绩并求其平均分, 那就需要定义100个变量并且要输入100次数据, 之后才能求解其平均成绩. 可能有人会说, 定义一个变量, 用100次循环将100个学生的成绩累加至求和变量中也可以求解平均成绩, 可如果日后要用这100个数据进行排序操作或求解100个数据中的最值, 我们就没有办法实现了.
[程序实现]
#include<stdio.h>
/* 数组a[]中存储了num个学生的成绩数据 */
double Average(short a[], unsigned short num)
{
unsigned short i = 0;
unsigned long S = 0;
while(i < num)
{
S += a[i];
i ++;
}
return (double)S / num;
}
/* */
int main()
{
/* 学生数量 */
short n;
printf("请输入学生的数量: ");
/* 增加输入容错机制 */
while(scanf("%hd", &n) != 1 || n < 1)
{
printf("请正确输入数据.\n");
while(getchar() != '\n') ;
printf("请输入学生的数量: ");
}
/* */
unsigned short i = 0;
short student[n];
while(i < n)
{
printf("第%hu个学生的成绩: ", i + 1);
while(scanf("%hd", student + i) != 1)
{
printf("请输入合法数据.\n");
printf("第%hu个学生的成绩: ", i + 1);
while(getchar() != '\n') ;
}
if(student[i] >= 0 && student[i] <= 150)
{
i ++;
}
else
{
printf("学生成绩应为0~150, 请重新输入.\n");
}
}
/* */
printf("%hd个学生的平均成绩为%.4lf.\n", n, Average(student, n));
/* */
return 0;
}