C++ C++;While循环,该循环在数组等于或太零时停止
我的比赛有点问题。我想要的是,当两个数组中的一个变成全部0时,循环将停止。当前,当两个数组都等于零时,循环停止 我认为问题在于,但没有解决方案的是,我在一个循环中有两个数组语句,即使array1(border1)得到了所有0,它也会从上到下运行 你觉得怎么样C++ C++;While循环,该循环在数组等于或太零时停止,c++,arrays,while-loop,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; boo
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[],字符串名[],int cap){
常量int hit=0;
int shot=0;
布尔元=假;
内部温度;
对于(int i=0;i cout关键是你必须在每次循环迭代时检查整个电路板的状态。如下所示:
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
}
}
void ShootAtShip(int board1[],int board2[],字符串名[],int cap){
对于(int i=0;i
}尤其是在编写游戏时,最好尝试将代码组织成函数。
我个人会这样做:
bool isGameOver(int board1[], int board2[], size_t cap)
{
bool lost1 = true;
bool lost2 = true;
for (size_t i = 0; i < cap && lost1 != false; ++i)
if (board1[i] != 0)
lost1 = false;
if (lost1)
return true;
for (size_t i = 0; i < cap && lost2 != false; ++i)
if (board2[i] != 0)
lost2 = false;
return lost2;
}
bool-isGameOver(内板1[],内板2[],尺寸上限)
{
bool lost1=真;
bool lost2=真;
对于(大小i=0;i
然后将其作为一个条件来中断循环
既然你使用C++,为什么不把这些板抽象成一个类?这样可以让你存储信息,比如每个板上有多少个船。< /P>
也可以考虑使用C++中的“代码> STD::数组< /代码>类模板,这样就不必通过数组大小,尝试使用 SsieZiT<< /Cord>或STD::SigZeT<<代码>数组索引。
应该<代码>(WON:TRUE)实际上是(WOR= = TRUE)
?是的,应该是这样,但这不会造成问题:D,更新代码。请格式化您的代码并删除所有不必要的空行。然后重试。请尊重其他用户。在发布之前,请始终花一些时间格式化您的代码。这次我是为您做的。干杯,伙计,下次会考虑的。好的,但是Do我必须在while循环中写入,以使其中断循环?更新的代码在这里