C ++网格问题

时间:2015-09-20 10:32:00

标签: c++

我在6x6网格中打印ascii框中的随机数字。打印网格时遇到问题。

我的所有方框和数字都在1列中打印出来,而不是有6列。一直在排除故障,但似乎无法找到问题。下面是代码。感谢您的帮助。

int main(void) 
{ 

    cout << "Magic Grid\n" << endl;

    int arrayxy [6][6];
    srand((unsigned)time(0));  
    int lowest=1111, highest=9999; 
    int range=(highest-lowest)+1; 

// Fill array with random values 
for (int i = 0; i < 6; ++i)
{
    for(int j = 0; j < 6; ++j)
    {
        arrayxy[i][j] = lowest+int(range*rand()/(RAND_MAX + 1.0));
    }
}

// Print array as grid
for (int i = 0; i < 6; ++i)
{
    for(int j = 0; j < 6; ++j)
    {
            cout << char(218);
            for (int y=0; y< 4; y++)
            {
                cout << char(196);
            }
            cout << char(191) <<endl;
            cout << char(179) << arrayxy[i][j] << char(179) << endl;
            cout << char(192);
            for (int z=0; z< 4; z++)
            {
                cout << char(196);
            }
            cout << char(217) <<endl;
    }
    cout << endl;
}

cout << endl;

}

1 个答案:

答案 0 :(得分:0)

在打印完所有列之后,您应该endl,而不是之前。

这就是我修复代码的方式,希望能够提供你想要拥有的代码。

为了记录,我专门将ASCII更改为*&,以使控制台结果更具可读性。您可以将它们更改回您希望再次使用这些字符的内容。

void WriteFrontLine(std::size_t count)
{
    for (int i = 0; i < count; i++)
    {
        cout << '*';
        cout << '&' << '&' << '&' << '&';
        cout << '*';
    }

    cout << endl;
}

void WriteEndLine(std::size_t count)
{
    for (int i = 0; i < count; i++)
    {
        cout << '*';
        cout << '&' << '&' << '&' << '&';
        cout << '*';
    }

    cout << endl;
}


int main(void)
{
    cout << "Magic Grid\n" << endl;

    int arrayxy[6][6];
    srand((unsigned)time(0));
    int lowest = 1111, highest = 9999;
    int range = (highest - lowest) + 1;

    // Fill array with random values 
    for (int i = 0; i < 6; ++i)
    {
        for (int j = 0; j < 6; ++j)
        {
            arrayxy[i][j] = lowest + int(range*rand() / (RAND_MAX + 1.0));
        }
    }

    // Print array as grid
    for (int i = 0; i < 6; ++i)
    {
        WriteFrontLine(6);

        for (int j = 0; j < 6; ++j)
        {
            cout << '*' << arrayxy[i][j] << '*';
        }

        cout << endl;

        WriteEndLine(6);

        cout << endl;
    }
    cout << endl;
}

enter image description here