C++While循环,如果数组等于零,则停止该循环
C++ While loop that stops if an array is equal too zero
我的游戏有点问题。我想要的是,当两个数组中的一个变成全部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
}
}
}
尤其是在编写游戏时,最好尝试将代码组织成函数。就我个人而言,我会这样做:
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;
}
然后将其作为条件来中断循环。
既然你使用的是c++,为什么不把这些板抽象成一个类呢?这将允许您存储信息,例如每个板上还剩多少艘船。
还可以考虑在c++中使用std::array
类模板,这样就不必单独传递数组大小,并尝试使用size_t
或std::size_t
进行数组索引。
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 使用for循环检查数组中的重复项
- 并行用于C++17中数组索引范围内的循环
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 程序在遍历所有值之前离开循环. 数组的
- 在C++中循环数组时访问结构属性
- 如何创建循环数组
- 查找 for 循环数组C++中存在最大值和最小值的值
- 有没有办法在 c++ 中创建循环数组
- OpenMP-每个线程的循环/数组界限
- 循环数组 - 从最后一个跳到第一个,反之亦然
- 循环数组时显示'stack smashing detected abc2 terminated Aborted'
- 使用循环数组实现矢量
- 为什么在循环数组时会得到奇怪的整数
- 循环数组-超出值
- 用于循环数组赋值的C++.正在返回垃圾邮件
- 在RapidJson中循环数组并获取对象元素
- 对于循环数组迭代,if循环测试索引是否为真/假,计算结果不正确
- c++循环/数组
- 有没有一种方法可以简化这个c++整数循环数组?