当n为非4倍数的偶数(即4m+2形)时怎么做啊?? 就差这种情况了 按照上面的做法 好像不行啊
这是我的程序 谢谢。
#include<iostream>
#include<iomanip>
using namespace std;
#define MAX 20
int Matrix[MAX][MAX];
void oddMatrix(int row1,int col1,int order,int cnt)
{
int row,col,count;
row=row1;
col=col1+order/2;
for(count=cnt;count<=cnt+order*order-1;count++)
{
Matrix[row][col]=count;
if(count%order==0)
row++;
else
{
row=(row==row1)?(order-1+row1):row-1;
col=col1+(col==col1+order-1)?col1:col+1;
}
}
}
void addMatrix(int row1,int col1,int order,int NUM)
{
int i,j;
for(i=0;i<order;i++)
for(j=0;j<order;j++)
Matrix[i+row1][j+col1]=Matrix[i][j]+NUM;
}
main()
{
int i,j,u,t,current;
int order=1;
int count=1;
int row1,col1;
i=0;
j=0;
cout<<"Enter a number"<<endl;
cin >>order;
if(order%4==0)
{
for(i=0;i<order;i++)
for(j=0;j<order;j++)
{
Matrix[i][j]=count;
count++;
}
for(i=0;i<order;i++)
for(j=0;j<order;j++)
{
if(i==j||i+j==order-1)
Matrix[i][j]=order*order+1-Matrix[i][j];
}
}
else if(order%2!=0)
oddMatrix(0,0,order,1);
else
{
oddMatrix(0,0,order/2,1);
addMatrix(order/2,order/2,order/2,order*order/4);
addMatrix(0,order/2,order/2,order*order/2);
addMatrix(order/2,0,order/2,order*order/4*3);
u=order/2;t=(order+2)/4;
for(i=0;i<order;i++)
for(j=0;j<order;j++)
{
if(j<t||j>order-t+2)
{
current=Matrix[i][j];
Matrix[i][j]=Matrix[i+u][j];
Matrix[i+u][j]=current;
}
}
current=Matrix[t][1];
Matrix[t][1]=Matrix[t+u][1];
Matrix[t+u][1]=current;
current=Matrix[t][t];
Matrix[t][t]=Matrix[t+u][t];
Matrix[t+u][t]=current;
}
for(row1=0;row1<order;row1++)
{
for(col1=0;col1<order;col1++)
cout<<setw(4)<<Matrix[row1][col1];
cout<<endl;
}
return 0;
}