c++:螺旋输出

#include<iostream>
#include<iomanip>
using namespace std;
void Spiraloutput() {
    cout << "■■■■■■■■■■■■■■■■■■■" << endl;
    cout << "■             螺旋输出             ■" << endl;
    cout << "■■■■■■■■■■■■■■■■■■■" << endl;
    cout << "请输入数字n:";
    int n, sz;
    cin >> n;
    sz = sqrt(n);
    // 找到一个最小方阵
    while (sz*sz < n) {
        sz++;
    }
    int **a = new int*[sz];
    for (int i = 0; i < sz; i++) {
        a[i] = new int[sz];
    }
    for (int i = 0; i < sz; i++) {
        for (int j = 0; j < sz; j++) {
            a[i][j] = 0;
        }
    }
    int x, y;
    // 如果是偶数,就在中心的左上一格,如果是奇数,则在中心
    if (sz % 2 == 0) {
        x = sz / 2 - 1;
        a[sz / 2 - 1][sz / 2 - 1] = n;
        y = x;
    }
    else {
        x = sz / 2;
        a[sz / 2][sz / 2] = n;
        y = x;
    }
    int cnt = n;
    int loop = 1;
    // 向右移动loop次,向下移动loop次,向左移动loop+1次,向上移动loop+1次,然后依次循环
    while (cnt > 0) {
        for (int i = 0; i < loop && y < sz; i++) {
            if (cnt <= 1) {
                goto here;
            }
            a[x][++y] = --cnt;
        }
        for (int i = 0; i < loop && x < sz; i++) {
            if (cnt <= 1) {
                goto here;
            }
            a[++x][y] = --cnt;
        }
        loop++;
        for (int i = 0; i < loop && y - 1 >= 0; i++) {
            if (cnt <= 1) {
                goto here;
            }
            a[x][--y] = --cnt;
        }
        for (int i = 0; i < loop && x - 1 >= 0; i++) {
            if (cnt <= 1) {
                goto here;
            }
            a[--x][y] = --cnt;
        }
        loop++;
    }
here:
    cout << endl;
    for (int i = 0; i < sz; i++) {
        for (int j = 0; j < sz; j++) {
            if (a[i][j] == 0) {
                cout << setw(8) << " ";
            }
            else {
                cout << setw(8) << a[i][j];
            }
        }
        cout << endl;
    }
    for (int i = 0; i < sz; i++) {
        delete[]a[i];
    }
    a = nullptr;
}
int main() {
    Spiraloutput();
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/CoderMaximum/article/details/86220810