c++ - 对于循环数组迭代,if循环测试索引是否为真/假,错误地评估真

标签 c++ arrays if-statement for-loop switch-statement

我正在开发一个库存系统,作为对我目前所知道的 c++ 数量的挑战,我正在使用一个带有枚举索引的数组,并使用值 true 或 false 进行初始化。这是代码:

using namespace std;

enum items
{
    LASER_RIFLE,
    LASER_SWORD,
    LASER_PISTOL,
    PLASMA_LAUNCHER,
    MAX_ITEMS
};


void playerInventory()
{
    bool items[MAX_ITEMS];
    items[LASER_RIFLE] = true;
    items[LASER_SWORD] = false;
    items[LASER_PISTOL] = false;
    items[PLASMA_LAUNCHER] = true;

    int itemName;
    for (int item = 0; item <= MAX_ITEMS; ++item)
        if (items[item] == true)
        {
            switch (itemName)
            {
            case 1:
                cout << "Laser Rifle\n";
                break;
            case 2:
                cout << "Laser Sword\n";
                break;
            case 3:
                cout << "Laser Pistol\n";
                break;
            case 4:
                cout << "Plasma Launcher \n";
                break;
            }
        }
        else
            cout << "Not in Inventory\n";
}

该语句仅对激光手枪评估为真,对其他一切评估为假。我不明白这是为什么。

最佳答案

  • 您正在切换 itemName .您应该切换为 item

  • 默认枚举从 0 开始,而不是 1。您的案例应该从 0 开始。

  • 在 for 循环中你必须检查 <不是 <= .

结果如下:

#include <iostream>
using namespace std;

enum items
{
    LASER_RIFLE,
    LASER_SWORD,
    LASER_PISTOL,
    PLASMA_LAUNCHER,
    MAX_ITEMS
};


void playerInventory()
{
    bool items[MAX_ITEMS];
    items[LASER_RIFLE] = true;
    items[LASER_SWORD] = false;
    items[LASER_PISTOL] = false;
    items[PLASMA_LAUNCHER] = true;

    int itemName;
    for (int item = 0; item < MAX_ITEMS; ++item) {
        if (items[item] == true)
        {
            switch (item)
            {
            case 0:
                cout << "Laser Rifle\n";
                break;
            case 1:
                cout << "Laser Sword\n";
                break;
            case 2:
                cout << "Laser Pistol\n";
                break;
            case 3:
                cout << "Plasma Launcher \n";
                break;
            }
        }
        else {
            cout << "Not in Inventory\n";
        }
    }
}

int main() {
    playerInventory();
    return 0;
}

参见:ideone

关于c++ - 对于循环数组迭代,if循环测试索引是否为真/假,错误地评估真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31958597/

相关文章:

互斥体上的 C++ 并发段错误

c++ - 从原始内存和类分析器中推断原始类型

php - 如何从数组变量PHP中获取指定列到动态变量中

linux - 如何在 while 循环中实现 IF 语句,并保持 while 循环无限期运行? ( bash )

python - 在 Python 中组合 except 和 else

c++ - 具有 C++ 数据结构的 C 代码

c++ - 在 Visual Studio C++ 2013 中设置图形

arrays - Swift - 从类中追加数组时遇到问题

javascript - JQuery - 解析类,然后使用 if 语句仅修改一个

C:转换 A ? B : C 进入 if (A) B else C