/**
* n阶幻方程序
* 完成者:lizemin
* 完成日期:2011.7.15
* 编译环境:VC6.0
*/
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
void showFangzhen(int n)
{
if(!(n%2))
return;
int i,j,**array;
//为指针分配动态内存
array=new int*[n];
for(i=0; i<n; i++)
{
array[i] = new int[n];
}
//初始化数组
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
array[((n-1)/2+i-j+n)%n][(3*n-1+j-2*i)%n]=i*n+j+1;
//or
//array[(n+2*i-j)%n][((n-1)/2+n+j-i)%n]=i*n+j+1;
}
}
//输出n阶幻方
cout<<n<<"阶幻方:"<<endl;
for(i=0; i<n; i++)
{
for(j=0;j<n;j++)
{
cout<<setw(int(log10(n*n))+2)<<array[i][j];
}
cout<<endl;
}
cout<<endl;
//释放动态内存
for(i=0; i<n; i++)
{
delete[] array[i];//原来是 delete array[i];
}
delete[] array;
}
int main()
{
int n;
cout<<"输入n阶幻方....";
cin>>n;
showFangzhen(n);
cout<<"Press enter to quit!";
cin.get();
return 0;
}