#include<stdio.h>
int main()
{
int a[10][10];
int i,j,ok,n,m;
for(i = 0;i < 10;i++)
/*给备用的数组做初始化*/
{
for(j = 0;j < 10;j++)
a[i][j] = 0;
}
ok = 0;
/*限定输入的数必须满足要求*/
while(ok == 0)
{
printf("Please input a number as the value of n:(必须是10以内的奇数)\n");
scanf("%d",&n);
if(n % 2 != 0 && n > 0 && n < 10 )
ok = 1;
else
ok = 0;
}
i = 0;
j = n/2;
a[i][j] = 1;
for(m = 2;m <= n*n;m++)
/*因为1已经放好了,所以我们从2开始放*/
{
if((i == 0) && (j != n-1))
/*算法中的第3步*/
{
i = n-1;
j = j+1;
if(a[i][j] == 0)
/*算法中的第7步*/
a[i][j] = m;
else
{
i = 1;
j = j - 1;
a[i][j] = m;
}
}
else if((i != 0) && (j == n-1))
/*算法中的第4步*/
{
i = i-1;
j = 0;
if(a[i][j] == 0)
/*算法中的第7步*/
a[i][j] = m;
else
{
i = i + 1;
j = n - 1;
a[i][j] = m;
}
}
else if((i == 0) && (j == n-1))
/*算法中的第5步*/
{
i = n-1;
j = 0;
if(a[i][j] == 0)
/*算法中的第7步*/
a[i][j] = m;
else
{
i = 1;
j = n - 1;
a[i][j] = m;
}
}
else
/*算法中的第6步*/
{
i = i-1;
j = j+1;
if(a[i][j] == 0)
/*算法中的第7步*/
a[i][j] = m;
else
{
i = i + 2;
j = j - 1;
a[i][j] = m;
}
}
}
printf("%d阶魔方阵:\n",n);
for(i = 0;i < n;i++)
/*输出数组*/
{
for(j = 0;j < n;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
return 0;
}