虽然但是你可以试试这个:
```cpp
#include<iostream>
using namespace std;
int n,a[40][40],h,l;
int main(){
cin>>n;
a[0][n/2]=1;
h=0;
l=n/2;
for(int i=2;i<=n*n;i++){
if(h==0&&l!=n-1){
a[n-1][l+1]=i;
h=n-1;
l++;
}
else if(l==n-1&&h!=0){
a[h-1][0]=i;
h--;
l=0;
}
else if(h==0&&l==n-1){
a[h+1][l]=i;
h++;
}
else if(h!=0&&l!=n-1){
if(a[h-1][l+1]==0&&h-1>=0&&l+1<=n){
a[h-1][l+1]=i;
h--;
l++;
}
else{
a[h+1][l]=i;
h++;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++) cout<<a[i][j]<<' ';
cout<<endl;
}
}
```
by manyc @ 2023-08-09 11:51:15
```cpp
#include<iostream>
using namespace std;
int N,cnt=2,index[2];
int main()
{
cin>>N;
int list[40][40]={0};//存储幻方的数据(数组应初始化)
list[0][int(N/2)] = 1;//根据数组0开始,直接向下取整
index[0] = 0;//[0]表示行数
index[1] = int(N/2);//[1]表示列数
while(cnt <= N*N)//没有等于会少输出一个数
{
if(index[1] != N-1 && index[0] == 0)//1
{
list[N-1][index[1]+1] = cnt;
index[1]=index[1]+1;
index[0]=N-1;
}
else if(index[1] == N-1 && index[0] != 0)//2
{
list[index[0]-1][0] = cnt;
index[1]=0;
index[0]=index[0]-1;
}
else if(index[1] == N-1 && index[0] ==0)//3
{
list[index[0]+1][index[1]] = cnt;
//index[0]=index[0];
index[0]=index[0]+1;
}
else if(index[1] != N-1 && index[0] != 0)//3
{
if(list[index[0]-1][index[1]+1]==0)
{
list[index[0]-1][index[1]+1] = cnt;
index[1]=index[1]+1;
index[0]=index[0]-1;
}
else
{
list[index[0]+1][index[1]] = cnt;
//index[0]=index[0];
index[0]=index[0]+1;
}
}
cnt++;
}
for(int i=0;i<N;i++){
for(int j=0;j<N;j++)
{
cout<<list[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
```
@[CVcoding](/user/894069)
by liuzihao1234 @ 2023-08-10 10:57:35
@[liuzihao1234](/user/1043752) 谢了
by CVcoding @ 2023-08-10 20:06:00