C++ While 循环在数组为零时停止

标签 c++ arrays while-loop

我的游戏有点问题。我想要的是当两个数组中的一个变为全 0 时循环将停止。目前,当两个数组都为零时,循环停止。

我认为问题所在但没有​​解决方案是我在一个循环中有两个数组语句,即使 array1(border1) 已全为 0,它也会从顶部到底部运行。

你怎么看?

void ShootAtShip(int board1[], int board2[], string names[], int cap) {
    const int hit = 0;
    int shot = 0;
    bool won = false;
    int temp;

    for (int i = 0; i < cap; i++) {
        while ((board1[i] != 0 || board2[i] != 0)) { //detects if any board has all their ships shot down
            cout << names[1] << " set a position to shoot." << endl;
            cin >> shot;
            temp = shot;

            while ((shot >= cap) || (shot < 0)) {       //detects if the number is allowed
                cout << "That number is not allowed, "<<  names[1] << " set a position to shoot." << endl;
                cin >> shot;
            }

            if (board1[shot] != 0) {
                board1[shot] = 0;
                cout << "Hit!" << endl;
            }
            else {
                cout << "You missed." << endl;
            }

            shot = 0;
            cout << names[0] << " set a position to shoot." << endl;
            cin >> shot;

            while ((shot >= cap) || (shot < 0)) {       //detects if the number is allowed
                cout << "That number is not allowed, " << names[0] << " set a position to shoot." << endl;
                cin >> shot;
            }

            if (board2[shot] != 0) {
                board2[shot] = 0;
                cout << "Hit!" << endl;
            }
            else {
                cout << "You missed." << endl;
            }
        }
    }

    cout << "Testing is while loop stops";
}

最佳答案

关键是你必须在每次循环迭代时检查整个板的状态。像这样:

void ShootAtShip(int board1[], int board2[], string names[], int cap) {

for (int i = 0; i < cap; i++) 
{
    while ( 1 )
    {
       bool board1HasShips = false;
       bool board2HasShips = false;
       for ( int j = 0; j < cap; j++ ) 
       { 
          if ( board1[j] != 0 ) 
          { 
             board1HasShips = true;
             break;
          }
       }
       for ( int j = 0; j < cap; j++ ) 
       { 
          if ( board2[j] != 0 ) 
          { 
             board2HasShips = true;
             break;
          }
       }

       if ( !board1HasShips || !board2HasShips ) break; 

       // past this point we know that both boards have ships.
       // shoot at ships
    }
}

关于C++ While 循环在数组为零时停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26088114/

相关文章:

c++ - 如何在windows下确定删除文件(文件锁问题)?

c++ - 了解 SFINAE 示例

c - 数组声明,并且不使用中间索引

php - while循环与foreach

java - While 循环无法正常工作,无限循环?

C++11 - move 包含文件流的对象

C++ 17 : Using alias template bug in gcc?

javascript - 无法在 JavaScript 中访问内部 json 数组,但可以通过控制台记录完整的 json

arrays - 数组通常在较低级别上如何工作?

c++ - 迭代器失效