开发者

For loop logic error?

开发者 https://www.devze.com 2023-02-14 06:47 出处:网络
void GameBoard::print(const GameBoard& computerBoard) { Grid[0][0] = \'1\'; Grid[0][1] = \'2\'; Grid[1][0] = \'3\';
void GameBoard::print(const GameBoard& computerBoard)
{
Grid[0][0] = '1';
Grid[0][1] = '2';
Grid[1][0] = '3';

int i, j;
int sides = SIZE;

cout << "        Your bombs:                    Your navy:" << endl << endl;

for(i=0; i<SIZE; i++)
{
    // prints your bombs
    cout << sides << "  ";
    for(j=0; j<SIZE; j++)
    {
        cout << computerBoard.Grid[i][j] << "  ";
    }
    cout << "    ";

    // prints your ships
    cout << sides << "  ";
    for(j=0; j<SIZE; j++)
    {
        cout << Grid[i][j] <开发者_如何学运维< "  ";
    }
    cout << endl << endl;
    sides--;
}

j = 0;
cout << "\n   ";

for(i=0; i<SIZE; i++)
{
    j = i + 'A';
    cout << (char)j << "  ";
}
cout << "       ";

for(i=0; i<SIZE; i++)
{
    j = i + 'A';
    cout << (char)j << "  ";
}
cout << endl << endl;

}

I am constructing a game like battleship, and need to change the for loop to read..

for(i=8;i>0;i--)

why does this produce an error?

Sorry if this doesnt make sense, Grid[0][0] should be on the bottom left, but it is currently at the top left.


I guess what you want is something like

for(i=SIZE-1; i>=0; i--)

because this is equivalent to

for(i=0; i<SIZE; i++)

both of these go from 0..SIZE-1 while

for(i=SIZE; i>0; i--)

goes from 1..SIZE (and so if you access an array of length SIZE using arr[i], will produce an error).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号