C语言二维数组周边元素平均值计算 - 代码示例
C语言二维数组周边元素平均值计算 - 代码示例
题目:
打开考生文件夹下的源程序文件prog1.c。在此程序中,定义了N×N的二维数组,并在主函数中赋值。请编写函数fun,函数的功能是:求出数组周边元素的平均值并作为函数值返回给主函数中的s。例如,若a数组中的值为:
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
则返回主程序后s的值应为3.375。
解答:
#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
总结:
本示例代码展示了如何使用 C 语言编写函数来计算二维数组周边元素的平均值。代码逻辑清晰易懂,并提供了详细的注释,方便读者理解和学习。
原文地址: https://www.cveoy.top/t/topic/ntCf 著作权归作者所有。请勿转载和采集!