输出"魔方阵"。所谓魔方阵是指这样的方阵,它的每一行、每一列和对角线之和均相等。
#include<stdio.h>
int main()
{int a[15][15], i, j, k,n=0;//校验输入的是不是偶数或者是不是超过了15while ((n % 2 == 0) || (n > 15) || (n==0)){printf("输入n的值,不能是偶数,不能超过15:");scanf("%d", &n);}//将数组用0初始化for (i = 1; i <= n; i++)for (j = 1; j <= n; j++)a[i][j] = 0;//建立魔方阵i = 1; j = (n+1) / 2;a[i][j] = 1;//i表行,j表列for (k = 2; k <= n * n; k++){i = i - 1; //行减1 列加1j = j + 1;//特殊情况if ((i < 1) && (j > n)){i = i + 2; //第1行第n列的元素之后的数j = j - 1;}else{if (i < 1)//单个行或列超出i = n;if (j > n)j = 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;
}