#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
int n;
cout<<"請輸入階數:";
cin>>n;
if(n<2 || 0==(n&1))
cout<<" 請輸入大於2的奇數!"<<endl;
else
{
int **a;
int i,j;
//new
a=new int *[n];
for(i=0;i<n;++i)
a[i]=new int [n];
//初始化
for(i=0;i<n;++i)
for(j=0;j<n;++j)
a[i][j]=0;
int r=0,c=n/2;
//填數字
for(i=1;i<=n*n;++i)
{
a[r][c]=i;
if(a[(r-1+n)%n][(c+1)%n]==0)
{
r=(r-1+n)%n;//右上
c=(c+1)%n;
}
else
r=(r+1)%n;//底下
}
cout<<endl;
//印
for(i=0;i<n;++i)
{
for(j=0;j<n;++j)
cout<<setw(5)<<a[i][j];
cout<<"\n";
}
i=n*(n*n+1)/2;
cout<<endl<<endl<<"每一條對角線.每一行.每一列, 數字總合都等於 "<<i<<endl<<endl;
//delete
for(i=0;i<n;++i)
delete []a[i];
delete []a;
}
return system("pause");
}
留言列表