n阶魔方数(此代码仅解决了 奇数阶的魔方数)
#include<stdio.h>
void main()
{
int i,j,k,n;
int num[100][100]={0};
printf("输入魔方阵的阶数:");
scanf("%d",&n);
j = 0;
k = n/2;
num[j][k]=1;
for(i=2;i<=n*n;i++)
{
if(j==0){
if(j==0&&k==n-1){
num[j+1][k]=i;
j++;
}
else{
num[n-1][k+1]=i;
k++;
j=n-1;
}
continue;
}
if(k==n-1){
num[j-1][0]=i;
j--;
k=0;
continue;
}
if(num[j-1][k+1]==0){
num[j-1][k+1] = i;
j--;
k++;
continue;
}
else{
num[j+1][k]=i;
j++;
continue;
}
}
for(i=0;i<n;i++){
for(j=0;j<n;j++)
printf("%2d ",num[i][j]);
printf("\n");
}
}