Magic square:That each row, each column and the sum of the diagonal elements are equal.
*******************************|8 1 6|
*******************************|3 5 7|
*******************************|4 9 2|
Magic matrix calculation rules ( row, column starting with 1 ):
(1)1 is placed in the first row, in the middle of a column;
(2)From 2 start to N*N the number in the following pattern : Each number of rows stored over the previous number of rows minus 1 and each number of the number of columns than the last column of the store plus 1;
(3)When a number of acts 1, the next few acts N;
(4)When N is a sequence number, the next sequence number is 1, the number of rows minus 1;
(5)According to the above rules determine the location of a number, or number of the last nth row 1th column, the next number just below the location for the number of the previous ( rows minus 1, the number of columns unchanged ).
// date:2020/3/3
// author:xiezhg5
#include <stdio.h>
int main(void)
{
int a[16][16],i,j,k,p,n;
p=1;
//判断条件(方阵不得超过16阶
while(p==1)
{
printf("请输入阶数:\n");
scanf("%d",&n);
if((n!=0)&&(n<=15)&&(n%2!=0))
p=0;
}
//建立魔方阵
for(i=1;i<=n;i++) //控制行数
for(j=1;j<=n;j++) //控制列数
a[i][j]=0; //使a[i][j]元素全为0
j=n/2+1;
a[1][j]=1; //把1放在第一行中间一列
for(k=2;k<=n*n;k++)
{
i=i-1; //新存放的数的行比前一数减一
j=j+1; //列数加一
if((i<1)&&(j>n))
{
i=i+2; //行数是一,下一个数行数是n
j=j-1;
}
else
{
if(i<1) i=n; //上一个数列数为n,行数减一
if(j>n) j=1; //列数为1
}
if(a[i][j]==0)
a[i][j]=k;
else
{
i=i+2;
j=j-1;
a[i][j]=k; //下一个数放在上一个数下面
}
}
//输出魔方阵
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%5d",a[i][j]);
printf("\n");
}
return 0;
}