为什么我的全局变量似乎没有改变?

用户12387817

我试图创建一个非常简单的 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;
}
基兰

在 main 开始时,您不小心重新声明 LVL 未分配给您的全局变量。调试器可能会将全局 LVL 初始化为 0,从而使您的损坏计算乘以零。

int LVL;
int main() {
    LVL = 1; //assigning to global
    int LVL = 1;//declaring a 'shadow' variable
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章