/******************
打印出一個魔方陣,所謂魔方陣提的是每一行,每一行以及對角線之和均相等。
******************/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int array[16][16];
int i, j, k, m, n;
m = 1;
while(m == 1)
{
printf("請輸入n(0 < n <15,n是奇數)\n");
scanf("%d",&n);
if(n != 0 && (n <= 15) && (n%2 != 0))
{
printf("矩陣階數是: %d\n",n);
m = 0;
}
}
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
array[i][j] = 0;
j = n/2 + 1;
array[1][j] = 1;
for(k = 2; k <= n*n; k++)
{
i = i - 1;
j = j + 1;
if((i < 1) && (j > n))
{
i = i + 2;
j = j - 1;
}
else{
if(i < 1)
i = n;
if(j > n)
j = 1;
}
if(array[i][j] == 0)
array[i][j] = k;
else{
i = i + 2;
j = j - 1;
array[i][j] = k;
}
}
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
printf("%5d",array[i][j]);
printf("\n");
}
system("pause");
return 0;
}
|