如何在while循环中测试多个数组,看看它们的下标值是否不等于某个值?
当任一数组中的所有下标都等于 0 时,我还需要分隔数组以结束循环。我认为这是可行的,但事实并非如此。
while(
(pl_health[0] !=0 && pl_health[1] !=0 && pl_health[2] !=0 &&
pl_health[3] !=0 && pl_health[4] !=0 && pl_health[5] !=0) ||
(enemy[0].health !=0 && enemy[1].health !=0 && enemy[2].health !=0 &&
enemy[3].health !=0 && enemy[4].health !=0 && enemy[5].health !=0)
)
如您所见,我尝试使用 paranthesese 和 or 运算符将 2 个数组分开。程序运行没有错误,但循环甚至没有迭代一次。即使某些下标不等于 0。
最佳答案
问题是你应该切换条件,最有可能的是(取决于你想做什么)。其中一位评论者指出,您的逻辑是“只有当每个玩家都有健康或每个敌人都有健康时才进行”。我完整地保留了答案的另一部分,因为它仍然相关。不过,我认为这是表达您想要的条件的 while 循环。
while(
(pl_health[0] !=0 || pl_health[1] !=0 || pl_health[2] !=0 ||
pl_health[3] !=0 || pl_health[4] !=0 || pl_health[5] !=0) &&
(enemy[0].health !=0 || enemy[1].health !=0 || enemy[2].health !=0 ||
enemy[3].health !=0 || enemy[4].health !=0 || enemy[5].health !=0)
)
在条件中进行如此多的检查的 while 循环不是这里的方法。更好的方法可能是这样的:
bool playerAlive = true, enemyAlive = true;
while (playerAlive && enemyAlive) {
// game logic etc
playerAlive = false;
enemyAlive = false;
for (int i=0; i<6; i++) {
if (pl_health[i] != 0) {
playerAlive = true;
}
if (enemy[i].health != 0) {
enemyAlive = true;
}
}
}
请注意,存储生命值的数组方法可能最多只适用于简单/小型游戏。当然,您可能希望从 for 循环中删除神奇的“6”并使其成为常量。
关于C++ while循环,测试多个数组的下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25101308/