【发布时间】: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;
}
【问题讨论】:
-
考虑在此处创建
struct或class来存储这些属性。不要只是将它们转储到main。 -
也可以使用
std::vector<int> potion = { ... },然后你可以for (int& p : potion)。 -
回复:
it's always stuck on the first number.- 你设置了int p = 0;并且永远不会改变它的值
标签: c++ arrays while-loop switch-statement