蒟蒻求助
查看原帖
蒟蒻求助
894069
CVcoding楼主2023/8/5 21:03
#include<iostream>
using namespace std;
int N,cnt=2,index[2];
int main()
{
    cin>>N;
    int list[40][40];//存储幻方的数据
    list[int(N/2)][0] = 1;//根据数组0开始,直接向下取整
    index[0] = int(N/2);
    index[1] = 0;
    while(cnt < N*N)
    {
        if(index[0] != N-1 && index[1] == 0)//1
        {
            list[index[0]+1][N-1] = cnt;
            index[0]=index[0]+1;
            index[1]=N-1;
        }
        else if(index[0] == N-1 && index[1] != 0)//2
        {
            list[0][index[1]-1] = cnt;
            index[0]=0;
            index[1]=index[1]-1;
        }
        else if(index[0] == N-1 && index[1] == 0)//3
        {
            list[index[0]][index[1]+1] = cnt;
            //index[0]=index[0];
            index[1]=index[1]+1;
        }
        else if(index[0] != N-1 && index[1] != 0)//3
        {
            if(list[index[0]+1][index[1]+1]==0)
            {
                list[index[0]+1][index[1]+1] = cnt;
                index[0]=index[0]+1;
                index[1]=index[1]+1;
            }
            else
            {
                list[index[0]][index[1]+1] = cnt;
                //index[0]=index[0];
                index[1]=index[1]+1;
            }
        }
        cnt++;
    }
    int ans=0;
    for(int i=0;i<N;i++)
        for(int j=0;j<N;j++)
        {
            cout<<list[i][j]<<" ";
            ans++;
            if(ans == N)
            {
                cout<<endl;
                ans = 0;
            }
        }
    return 0;
}
2023/8/5 21:03
加载中...