第一個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中文網其他相關文章!