用C语言编程求M×N二维数组的周边元素之和,并用函数实现
3个回答
展开全部
#include<stdio.h>
#define M 3
#define N 4
int matrixsum(int d[M][N])
{
int i,j,sum=0;
for(j=0;j<N;j++)
sum+=d[0][j];
for(i=1;i<M;i++)
sum+=d[i][N-1];
for(j=N-2;j>=0;j--)
{
if(M>1)
sum+=d[M-1][j];
}
for(i=M-2;i>0;i--)
{
if(N>1)
sum+=d[i][0];
}
return sum;
}
int main()
{
int i,j,sum;
int data[M][N];
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
scanf("%d",&data[i][j]);
}
}
sum=matrixsum(data);
printf("%d\n",sum);
return 0;
}
不管几维矩阵都满足条件
追问
谢谢!!
展开全部
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#define M 4
#define N 5
int fun( int a [M][N])
{
int i,j,sum=0;
for(i=0;i<M;i++)
for(j=0;j<N;j++)
if(i==0||i==M-1||j==0||j==N-1)
sum+=a[i][j];
return sum;
}
void main()
{
FILE *wf;
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;
system("CLS");
printf ("The original data is :\n ");
for(i=0; i<M;i++)
{for (j=0; j<N;j++)
printf("%6d ",aa[i][j]);
printf("\n ");
}
y=fun(aa);
printf("\nThe sun: %d\n ",y);
printf("\n ");
/******************************/
wf=fopen("out.dat","w");
fprintf (wf,"%d",y);
fclose(wf);
/*****************************/
}
#include<stdio.h>
#include<stdlib.h>
#define M 4
#define N 5
int fun( int a [M][N])
{
int i,j,sum=0;
for(i=0;i<M;i++)
for(j=0;j<N;j++)
if(i==0||i==M-1||j==0||j==N-1)
sum+=a[i][j];
return sum;
}
void main()
{
FILE *wf;
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;
system("CLS");
printf ("The original data is :\n ");
for(i=0; i<M;i++)
{for (j=0; j<N;j++)
printf("%6d ",aa[i][j]);
printf("\n ");
}
y=fun(aa);
printf("\nThe sun: %d\n ",y);
printf("\n ");
/******************************/
wf=fopen("out.dat","w");
fprintf (wf,"%d",y);
fclose(wf);
/*****************************/
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询