我的游戏有点问题。我想要的是当两个数组中的一个变为全 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/