首页 > 解决方案 > 为什么我的全局变量似乎没有改变?

问题描述

我正在尝试创建一个非常简单的 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;
}

标签: c++

解决方案


这不一定是您使用全局变量,尽管正如@NathanOliver 指出的那样,这是一种不好的做法。

您需要 intint LVL = 1;in中删除main()。您的全局值在原始代码中保持为 0,而您创建了一个新的本地范围LVL,即 1。但是,您的函数只会看到全局LVL,而不是本地。


推荐阅读