永发信息网

C++利用二维数组的方法打印一个n*n的数字螺旋方阵。这个数字方阵的特点是:以左上角1开始向下,数字以外圈向里按自然数顺序转圈递增,一直到中心位置的n2为止。例如n =3

答案:1  悬赏:70  手机版
解决时间 2021-04-26 07:48
  • 提问者网友:姑娘长的好罪过
  • 2021-04-25 20:32

1 8 7

2 9 6

3 4 5

最佳答案
  • 五星知识达人网友:佘樂
  • 2021-04-25 21:28

#include<iostream.h>
#include<process.h>
#include<iomanip.h>
int main()
{int N,*b,d,**a;
cout<<"please input a number of array:";
cin>>N;
if((b=new int[N*N])==NULL)
{cout<<"can't allocate more memory.";
exit(1);}
a=new int *[N];
for(int c=0;c<N;c++)
a[c]=new int[N];


for(int a1=0;a1<N;a1++)
for(int a2=0;a2<N;a2++)
a[a1][a2]=0;
for(int i=0;i<N*N;i++)
b[i]=i+1;


if(N%2)
a[(N-1)/2][(N-1)/2]=N*N;

i=0;
for(d=0;d<N/2;d++)
{

for(int j=0+d;j<N-1-d;j++)
a[0+d][j]=b[i++];

for(int k=0+d;k<N-d-1;k++)
a[k][N-1-d]=b[i++];

for(int l=N-d-1;l>0+d;l--)
a[N-1-d][l]=b[i++];

for(int m=N-1-d;m>=1+d;m--)
a[m][0+d]=b[i++];
}

cout<<endl;

for(a1=0;a1<N;a1++)
{ for(int a2=0;a2<N;a2++)
cout<<setw(4)<<a[a1][a2];
cout<<endl;
}
return 0;
}

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯