我遇到一个小问题,当数组board1[i]
或board2[i]
仅包含0时,似乎While循环不会停止。
编写while ((board1[i] == 0) || (board2[i] == 0))
是正确的,因为我想要的是当某些电路板只包含0时,我希望循环停止。
void ShootAtShip(int board1[], int board2[], string names[], int cap){
const int hit = 0;
int shot = 0;
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;
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;
}
}
答案 0 :(得分:0)
我想要的是当某些主板只包含0时我想要的 循环太停。
我想你写的与你想要的完全相反:
while ((board1[i] == 0) || (board2[i] == 0))
如果board1 [i]等于零,则上述将运行;如果board2 [i]等于零,则运行。如果你想停止,如果两者中的任何一个为零,你应该写
while (!((board1[i] == 0) || (board2[i] == 0)))
注意! (不)在开头。同样你也可以写
while (board1[i] != 0 && board2[i] != 0)
答案 1 :(得分:0)
只写而不是
while ((board1[i] == 0) || (board2[i] == 0))
如果你想要两个电路板需要同时为0时写
while (board1[i] != 0 && board2[i] != 0)
否则如果其中一个板需要为0才能退出
while (board1[i] != 0 || board2[i] != 0)
答案 2 :(得分:0)
你所说的是,如果任何一块电路板都保持零。你想说的是,直到一块板子没有,继续前进。
for (int i = 0; i < cap; i++){
while ((board1[i] == 0) || (board2[i] == 0)){ //ACTUALLY DETECTS IF EITHER
//BOARD HAS A ZERO AT INDEX i
此段错误。你从索引零开始并检查EITHER board1或board2在该索引中是否有0,然后你做while循环的东西UNTIL board1 [i]!= 0&amp;&amp; board2 [i]!= 0.这意味着一旦找到零指数,你就永远不会停止循环,这意味着游戏不会结束。
你需要做的是分别浏览每个数组,看看是否符合条件然后决定做什么。亲身?我在两个阵列中寻找一个。两个数组中都不是全零。这样你就不会寻找停止的理由。让你的程序变得懒惰:停止,除非有理由继续。
以下行中的某些内容,以查看是否全部为零:
bool boardOneAllZeroes = false;
bool boardTwoAllZeroes = false;
//So if board one is all zeroes OR board two is all zeroes, stop looping.
while(!boardOneAllZeroes && !boardTwoAllZeroes)
{
boardOneAllZeroes = true;
boardTwoAllZeroes = true;
//The above two lines basically say "This loop isn't going to keep
//going unless you give me a good reason to later on.
//Next we go through each index in both arrays looking for a one.
for(int i = 0; i < cap; i++)
{
//If we find a one in board one, then board one is not all zeroes.
//Set it back to false
if(board1[i] == 1)
{
boardOneAllZeroes = false;
}
//Same thing with board two.
if(board2[i] == 1)
{
boardTwoAllZeroes = false;
}
}
//Check to make sure both still have a one, because we don't need to keep going
//if both are all zeros.
if(!boardOneAllZeroes && !boardTwoAllZeroes)
{
do game things
}
}
基本上,你首先要说的是每次迭代&#34;直到我给出一个不这么认为的理由,董事会都是零&#34;。然后寻求证明董事会AREN&#39;全部为零。然后,如果其中任何一个都是零,那么就不要做任何事情并停止游戏。