下列程序定义了NXN的二维数组,并在主函数中赋值。请编写函数fun(),函数的功能是求出数组周边元素的平方和并作为函数值返回给主函数中的s。例如:若a数组中的值为
a=0 1 2 7 9
1 11 21 5 5
2 21 6 11 1
9 7 9 10 2
5 4 1 4 1
则返回主程序后s的值应为310。
注意:部分源程序给出如下。
请勿改动主函数main和其他函数中的任何内容,仅在函数fun的花括号中填入所编写的若干语句。
试题程序:
#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
#define N 5
int fun (int w[][N])
main()
int a[N][N]=0,1,2,7,9,1,11,21,5,5,2, 21,6,11,1,9,7,9,10,2,5,4,1,4,1;
int i,j;
int s;
clrscr();
printf("*****The array***+*\n");
for (i=0;i<N;i++)
for(j=0;j<N;i++)
printf("%4d",a[i][j]);
printf("\n");
s=fun(a);
printf("*****THE RESULT*****\n");
printf("The sum is:%d\n",s);
参考答案:int fun(int w[])[N])
{
int i,j,k=0;
int s=0;
for(i=0;i<N;i++)
for(j=0;j<N;j++)
if(i==0||i==N-1||j==0||j==N-1) /*只要下标中有一个为0或N-1,则它一定是周边元素*/
{s=s+w[i][j]*w[i][j]; /*将周边元素求平方和*/
}
return s; /*返回周边元素的平方和*/
}
解析: 该题采用逐一判断的方式,周边元素的下标一定有一个是0或N-1,且只要下标中有一个为0或N-1,则它一定是周边元素。