#include<stdio.h>
#include<assert.h>
#define ROW 3
void MagicSquare()
{
assert(ROW % 2 != 0);
int a[ROW][ROW] = { 0 };
int col = ROW / 2;
int row=0;
a[row][col] = 1;
for (int i = 2;i <= ROW* ROW;i++)
{
//上行
//row = (row-1+ROW)%ROW;
row = row > 0 ? row - 1 : ROW - 1;
//后列
col = (col + 1) % ROW;
if (a[row][col] != 0)
{
//下行(现在的下两行)
row = (row + 2) % ROW;
//同列(现在的前一列)
col = (col - 1 + ROW) % ROW;
}
a[row][col] = i;
}
for (int i = 0;i < ROW;i++)
{
for (int j = 0;j < COL;j++)
{
printf("%-3d", a[i][j]);
}
printf("\n");
}
}
int main()
{
MagicSquare();
}
上行和前列 “-”且括号内前和上+ROW
下行和后列“+”