【问题标题】:Using an Array in a while loop在 while 循环中使用数组
【发布时间】:2020-12-01 12:25:30
【问题描述】:

我一直在研究这个,这是一个回合制战斗系统的测试程序。除了 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;
}

【问题讨论】:

  • 考虑在此处创建structclass 来存储这些属性。不要只是将它们转储到main
  • 也可以使用std::vector&lt;int&gt; potion = { ... },然后你可以for (int&amp; p : potion)
  • 回复:it's always stuck on the first number. - 你设置了int p = 0; 并且永远不会改变它的值

标签: c++ arrays while-loop switch-statement


【解决方案1】:

我想你在使用药水后忘记加 p 了。这样做:

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

【讨论】:

  • 可能应该做p = std::max(3, p+1); 以避免索引出potions
【解决方案2】:

我假设你想在你用完所有药水后模拟药水用完。我还将稍微修改您的药水阵列以使其更简单。您应该使用 std::array 或 std::vector,这取决于您是否期望药水的数量大于您的初始药水数量。

改变

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

std::vector<int> potion{20, 15, 10, 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;

您可以做一些其他事情来重构此代码并使其更简洁,就像其他 cmets 中提到的那样,但这应该可以解决您的问题。

【讨论】:

  • 感谢您的反馈!我试试看
猜你喜欢
  • 2015-02-20
  • 2021-11-17
  • 2012-02-26
  • 2020-08-29
  • 2015-11-16
  • 2014-01-10
  • 1970-01-01
  • 2019-08-13
  • 2018-06-05
相关资源
最近更新 更多