如何解决在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;
您还可以执行其他一些操作来重构此代码,并使它更简洁,如其他注释中所述,但这应该可以解决您的问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。