C++ 表螺旋算法输出


#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int arraysize;
    cout<<"Size: ";
    cin>>arraysize;
    int a[arraysize][arraysize];
    int couter = 1, stepTop = 0, stepLeft = 1, stepBottom = 0, stepRight = 1;
    for(int iMain = 0; iMain < ((arraysize / 2) + 1); iMain++)
    {
        for(int i = stepTop; i < stepTop + 1; i++)
        {
            for(int j = stepTop; j < (arraysize - stepTop); j++)
            {
                a[i][j] = couter;
                couter++;
            }
        }
        stepTop++;
        if(iMain < (arraysize / 2))
        {
            for(int i = stepRight; i <= (arraysize - stepRight - 1); i++)
            {
                for(int j = (arraysize - stepRight); j < (arraysize - stepRight + 1); j++)
                {
                    a[i][j] = couter;
                    couter++;
                }
            }
            stepRight++;
            for(int i = (arraysize - 1 - stepBottom); i >= (arraysize - stepBottom - 1); i--)
            {
                for(int j = (arraysize - 1 - stepBottom); j >= stepBottom; j--)
                {
                    a[i][j] = couter;
                    couter++;
                }
            }
            stepBottom++;
            for(int i = (arraysize - stepLeft - 1); i >= stepLeft; i--)
                {
                for(int j = stepLeft; j < stepLeft; j++)
                {
                    a[i][j] = couter;
                    couter++;
                }
            }
            stepLeft++;
        }
    }

for(int i = 0; i < arraysize; i++)
    {
        for(int j = 0; j < arraysize; j++)
        {
            cout<<setw(arraysize)<<a[i][j];
            cout<<" ";
        }
        cout<<endl;
    }
    return 0;
}

问题是当程序输出数字时,它们如下所示:

Size: 6
     1      2      3      4      5      6
2686500     17     18     19     20      7
     1 2686336     27     28     21      8
4651536 2686512     30     29     22      9
     0     26     25     24     23     10
    16     15     14     13     12     11

返回的进程 0 (0x0) 执行时间 : 0.577 s按任意键继续。

图片 http://imgur.com/kjABBWr

只是一个小的更改:这个-> for(int j = stepLeft; j <= stepLeft; j++)到这个:for(int j = stepLeft-1; j < stepLeft; j++)

Ideone link: https://ideone.com/kR8nOZ

最新更新