c++ - 为什么我的全局变量似乎没有改变?
问题描述
我正在尝试创建一个非常简单的 RPG,并在我的程序顶部定义了几个全局变量。在函数 mage 中,我创建了一个方程来使用现有的全局变量来计算技能的伤害,这些变量的值应该根据函数进行更新。但是,在函数 monsterFight 中,我调用了 ability1 并且每次它都没有带走任何东西。即,它似乎带走了一个 0 的值。我不确定我做错了什么。
#include <iostream>
#include <string>
using namespace std;
int XP;
int HP;
int LVL;
int DMG;
string ability1Name;
float ability1;
void mage() {
HP = 10;
DMG = 5;
ability1Name = "Magic Bolt";
ability1 = (DMG * 1.1) * (LVL * 1.25);
}
void warrior() {
HP = 12;
DMG = 4;
}
void paladin() {
HP = 15;
DMG = 3;
}
void monsterStart(string monsterName, int level, int health) {
cout << "*************" << endl;
cout << "Name: " << monsterName << endl;
cout << "Level: " << level << endl;
cout << "HP: " << health << endl;
cout << "*************" << endl;
}
void monsterFight(int health) {
while (true) {
cout << "Select an ability: " << endl << "A. " << ability1Name << endl;
char abilitySelect;
cin >> abilitySelect;
if (abilitySelect == 'A') {
health - ability1;
cout << "Monster's HP: " << health << endl;
}
}
}
int main() {
int LVL = 1;
cout << "Welcome to the RPG!" << endl;
cout << "Please select a class: " << endl << "A. Mage\nB. Warrior\nC. Paladin" << endl;
char SL1;
cin >> SL1;
if (SL1 == 'A') {
mage();
cout << "You chose Mage!" << endl;
}
else if (SL1 == 'B') {
warrior();
cout << "You chose Warrior!" << endl;
}
else if (SL1 == 'C') {
paladin();
cout << "You chose Paladin!" << endl;
}
cout << "Let us have a tutorial by you defeating a practice monster!" << endl;
monsterStart("Dummy", 1, 10);
monsterFight(10);
return 0;
}
解决方案
这不一定是您使用全局变量,尽管正如@NathanOliver 指出的那样,这是一种不好的做法。
您需要 int
从int LVL = 1;
in中删除main()
。您的全局值在原始代码中保持为 0,而您创建了一个新的本地范围LVL
,即 1。但是,您的函数只会看到全局LVL
,而不是本地。
推荐阅读
- angular - 进行单个 API 调用并将响应存储在服务中,以便其他组件可以使用该响应而无需进行额外的 API 调用
- c# - 将 .net 框架移植到 .net 核心 Microsoft.Xrm.Sdk.Query
- regex - 如何删除所有以 $ 开头的行
- javascript - 使用 uiOutput 在闪亮的键盘上触发 actionButton
- ios - 如何修复特定控制器上的 alertView 方向?
- cakephp - CakePHP 3 对联合查询的结果进行分页
- java - 为什么即使我的文件位于正确的位置,我也会收到 filenotfound 异常?
- uwp - 在离线环境中将 Microsoft.NETCore.UniversalWindowsPlatform 从 6.1.7 升级到 6.1.9
- android - 最终签名的 apk 输出不适用于所有 android 设备
- java - 元 Java 的 Yocto 问题