C++ while循环,测试多个数组的下标

标签 c++ arrays while-loop

如何在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/

相关文章:

php - 如何确定在我的 PHP 表单中单击了哪个动态生成的提交按钮?

C++:使用owl重新编译旧代码

c++ - 不能声明只有一个参数的匿名对象

php - Symfony 不能决定哪个类需要

javascript - 如何使用其他对象中的值创建对象?

java - while循环与分号java

c++ - opengl 3+缓冲操作

c++ - 连接qt和matlab时出错

python - 算法题: Finding the cheapest flight

java - 打印文本文件的字符串