问题 问答题

下列程序定义了N×N的二维数组,并在主函数中赋值。请编写一个函数fun(),函数的功能是:求数组周边元素的平方和并作为函数值返回给主函数。例如,若数组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 <stdiib.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; j++)

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-i || j==0 || j==N-A)

{

s=s+w[i][j]*w[i][j];

}

return s;

}

解析:

该题采用逐一判断的方式,周边元素的下标一定有0或N-1,且只要下标中有一个为0或N-1,则它一定是周边元素。

判断题
单项选择题