产生奇数魔方阵

功能:产生奇数魔方阵。

  •  结果
3*3:
    8    1    6
    3    5    7
    4    9    2

5*5:
   17   24    1    8   15
   23    5    7   14   16
    4    6   13   20   22
   10   12   19   21    3
   11   18   25    2    9
// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "iomanip"
#define N 5

using namespace std;

int main()
{
    //system("color 0A");
    int i, j, key;
    int square[N + 1][N + 1] = { 0 };
    i = 0;
    j = (N + 1) / 2;
    for (key = 1; key <= N*N; key++)
    {
        if ((key % N) == 1)
            i++;
        else 
        {
            i--;
            j++;
        }
        if (i == 0)
            i = N;
        if (j > N)
            j = 1;
        square[i][j] = key;
    }
    for (i = 1; i <= N; i++) 
    {
        for (j = 1; j <= N; j++)
            cout << setw(5) << square[i][j];
        cout << endl;
    }
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u012366767/article/details/81631344