打开考生文件夹下的源程序文件prog1c。在此程序中定义了N×N的二维数组并在主函数中赋值。请编写函数fun函数的功能是:求出数组周边元素的平均值并作为函数值返回给主函数中的s。例如若a数组中的值为: 0 1 2 7 9 1 9 7 4 5 2 3 8 3 1 4 5 6
以下是一个可能的解答:
#include <stdio.h>
#define N 5
float fun(int a[N][N]) {
float sum = 0;
int count = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == 0 || i == N-1 || j == 0 || j == N-1) {
sum += a[i][j];
count++;
}
}
}
return sum / count;
}
int main() {
int a[N][N] = {
{0, 1, 2, 7, 9},
{1, 9, 7, 4, 5},
{2, 3, 8, 3, 1},
{4, 5, 6, 8, 2},
{5, 9, 1, 4, 1}
};
float s = fun(a);
printf("The average of the elements at the border of the array is: %.3f\n", s);
return 0;
}
在函数fun中,我们使用两个循环遍历数组的所有元素。如果一个元素的行坐标或列坐标等于0或N-1(即在数组的周边),则将其值加入到一个累加器sum中,并增加一个计数器count。最后,函数返回sum/count作为数组周边元素的平均值。
在主函数中,我们定义一个5x5的数组,并将其赋值为题目中给出的数组。然后调用函数fun来求出数组周边元素的平均值,并将其赋值给变量s。最后,我们在屏幕上输出变量s的值。结果应该为:
The average of the elements at the border of the array is: 3.375
``
原文地址: https://www.cveoy.top/t/topic/ckI9 著作权归作者所有。请勿转载和采集!