首页 >电脑教程 >电脑知识 >返回以二维数组周边元素之和为函数值

返回以二维数组周边元素之和为函数值

王林
王林转载
2024-01-22 22:48:20431浏览

返回以二维数组周边元素之和为函数值

返回以二维数组周边元素之和为函数值

第一个for循环用于计算矩阵最上一行和最下一行的总和,第二个for循环则计算除两头元素以外的最左一列和最右一列的元素的和。最后,将这两个求和结果相加得到周边元素的和。

〔源程序〕

#include

#include

#define M 4

#define N 5

int fun(int a[M][N])

{int sum=0,i;

for(i=0;i

sum+=a[0][i]+a[M-1][i];

for(i=1;i

sum+=a[i][0]+a[i][N-1];

return sum ;

}

main()

{ int aa[M][N]={{1,3,5,7,9},

{2,9,9,9,4},

{6,9,9,9,8},

{1,3,5,7,0}};

int i,j,y;

clrscr();

printf("The original data is :\n");

for(i=0;i

{for(j=0;j

printf("\n");

}

y=fun(aa);

printf("\nThe sum: %d\n",y);

printf("\n");

}

二维数组靠边元素之和

private function Anyl(A()() AS INTEGER,byval m as integer,byval n as integer) as long

tol=sum_side(A,m,n)

print tol

if m=n then

sd=Diag(A,m)

sid=InDiag(A,m)

print sd

print sid

else

print "m≠n"

end if

end function

private function Sum_side(A()() AS INTEGER,byval m_side as integer,byval n_side as integer) as long

dim sum as long

sum=0

n_side=n_side-1

for i=0 to n step 1

sum=sum+A(0)(i)

next i

m=m-2

for i=1 to m step 1

sum=sum+A(i)(0)

sum=sum+A(i)(n)

next i

m=m+1

for i=0 to n step 1

sum=sum+A(m)(i)

next i

sum_side=sum

end function

private function Diag(A()() AS INTEGER,byval m as integer) as long

dim Sum_Diag as long

m=m-1

Sum_Diag=0

FOR i=0 to m step 1

Sum_Diag=Sum_Diag+A(i)(i)

next i

Diag=Sum_Diag

end function

private function InDiag(A()() AS INTEGER,byval m as integer) as long

dim Sum_InDiag as long

m=m-1

Sum_Diag=0

FOR i=0 to m step 1

Sum_InDiag=Sum_InDiag+A(i)(m-i)

next i

InDiag=Sum_InDiag

end function

以上是返回以二维数组周边元素之和为函数值的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:docexcel.net。如有侵权,请联系admin@php.cn删除