大家都知道魔方阵问题,现要求输入一个奇数N,输出一个N*N的魔方阵。(魔法阵:各行、列、对角线加起来等于同一个数)
输入:3
输出:8 1 6
3 5 7
4 9 2
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int N=0;
while(N%2==0)
{
printf("please input:");
scanf("%d",&N);
}
int i, j, key;
int square[100][100] = {0};
i = 0;
j = (N+1) / 2;
for(key = 1; key <= N*N; key++) {
if((key % N) == 1)
i++;
else {
i--;
j++;
}
if(i == 0)
i = N;
if(j > N)
j = 1;
square[i][j] = key;
}
for(i = 1; i <= N; i++)
{
for(j = 1; j <= N; j++)
printf("%2d ", square[i][j]);
printf("\n");
}
return 0;
}
-----------------------------------------------------------------
#include<iostream.h>
#include<stdio.h>
#define N 100
void main()
{
int i,a[N][N],j,t,n;
for(i=0;i<N;i++)
for(j=0;j<N;j++)
a[i][j]=0;
cin>>n;
if(n%2==0)
cout<<"请重新输入:\n";
else
{
i=0;
j=n/2;
a[i][j]=1;
for(t=2;t<=n*n;t++)
{
i=i-1;
j=j+1;
if(i<0&&j==n)
{
i=i+2;
j=j-1;
}
else
if(i<0)
i=n-1;
if(j==n)
j=0;
if(a[i][j]==0)
a[i][j]=t;
else
{
i=i+2;
j=j-1;
a[i][j]=t;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%4d",a[i][j]);
cout<<endl;
}
}
}