编写程序,打印出N阶魔阵(N个奇数)

来源:互联网 发布:苹果电脑视频制作软件 编辑:程序博客网 时间:2024/05/21 07:49
 例     编写程序,打印出N阶魔阵(N个奇数)。如N=3和 5时
 8  1  6 
 3  5  7 
 4  9  2
 
 17  24  1  8  15 
 23  5  7  14  16 
 4  6  13  20  22 
 10  12  19  21  3 
 11  18  25  2  9
 
#include <cstdio>#include <iostream>#include <cstring>#include <cstdlib>using namespace std;int main(){    int a[100][100] = {0};    int i, j, n, m, i1, j1;    i = 0, j = n / 2;    cin>>n;        memset(a,0,sizeof(a));        a[0][n/2]=1;        i=0;        j=n/2;    for(m = 2; m <= n * n; m++)    {        i1 = i;/*移动之前的行列位置
 j1 = j; */
      if(i == 0)            i = n-1;      else        i--;      if(j == n - 1)        j = 0;      else        j++;     if(a[i][j] == 0)     a[i][j] = m;     else     {        a[i1 + 1][j1] = m;        i = i1 +1;        j = j1;     }    }     for(i1 = 0; i1 < n; i1++)        for(j1 = 0;j1 < n; j1++)           {               if(j1 == n -1)                cout<<a[i1][j1]<<endl;               else                cout<<a[i1][j1]<<'\t';           }    return 0;}