在while循环中使用数组

问题描述

我一直在努力,这是基于回合制战斗系统的测试程序。除if语句外,其他所有程序都运行良好。再次选择后,它应该使用下一个数字,但是它始终卡在第一个数字上。如果您有更有效的方法,将不胜感激。

#include <iostream>
#include <cmath>
#include <string>
#include <cstdlib>
#include <iomanip>

using namespace std;

int main()
{
    int item;
    int potion[] = { 20,15,10,5 };
    int p = 0;
    int battle;
    int health = 100;
    int attack = 25;
    int ehealth;
    float eattack = 20;
    int magic = 50;
    ehealth = 100;
    cout << "1 attack,2 attack with magic,3 Guard attack,4 Use items" << endl;
    while (ehealth > 0) {
        cin >> battle;
        switch (battle) {
        case 1: {
            cout << "You did " << attack << " damage!\n" << endl;
            ehealth = ehealth - attack;
            break;
        }
        case 2: {
            cout << "You used magic doing " << magic << " damage!\n" << endl;
            ehealth = ehealth - magic;
            break;
        }
        case 3: {
            cout << "You guard against the the attack!\n" << endl;
            health = health - (eattack / 10);
            break;
        }
        case 4: {
            cout << "Pick an item.\n 1. potion\n" << endl;
            cin >> item;
            if (item == 1) {
                cout << "You recovered " << potion[p] << " Hp" << endl;
                health = health + potion[p];
            }
            break;
        }
        }
        cout << "The enemy attacks!\n" << endl;
        health = health - eattack;
        cout << "Enemy Health: " << ehealth << endl;
        cout << "Your Health: " << health << endl;
    }
    return 0;
}

解决方法

我认为您忘了使用药水后添加到p中。这样做:

cout<<"You recovered "<< potion[p]<<" Hp"<<endl;
health = health + potion[p];
++p;
,

我假设一旦使用完所有药水,您就想建模药水用尽。我还将略微修改您的药水数组以使其更简单。您应该使用std :: array或std :: vector,具体取决于您是否期望药水的数量大于初始药水的数量。

更改

int potion[] = { 20,15,10,5 };

收件人

std::vector<int> potion{20,5}:

在使用药水的情况下,添加一些逻辑以检查药水是否不足,并在使用药水后递增p。

case 4:
  if (p >= potion.size())
  {
    std::cout << "You're out of potions!" << std::endl;
    continue;
  }
  cout << "Pick an item.\n 1. potion\n" << endl;
  cin >> item;
  if (item == 1) {
     cout << "You recovered " << potion[p] << " Hp" << endl;
     health = health + potion[p];
  }
  break;

您还可以执行其他一些操作来重构此代码,并使它更简洁,如其他注释中所述,但这应该可以解决您的问题。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...