【问题标题】:Interger not updating value in switch function in C++整数不更新 C++ 中 switch 函数中的值
【发布时间】:2020-08-07 06:45:05
【问题描述】:

这里有点像一个完整的初学者。

我是从 C++ 开始,并且是一般编程,所以,我正在尝试为文本 RPG 格斗游戏制作一个粗略的菜单,以练习条件。

但是,这些值不会自行更新。代码如下:

int main() {

    cout << "Wild Ogre attacked!" << endl << endl;
    int ogreHP = 350;
    int HP = 100;
    int Stamina = 100;
    int Magicka = 100;

    while (ogreHP > 1) {
    cout << "HP: " << HP << endl;
    cout << "Stamina: " << Stamina << endl;
    cout << "Magicka: " << Magicka << endl << endl;

    cout << "Ogre HP: " << ogreHP << endl << endl;

    cout << "What are you going to do? " << endl;
    cout << "1.\tAttack." << endl;
    cout << "2.\tMagicka." << endl;
    cout << "3.\tTactics." << endl;
    cout << "4.\tBag." << endl;
    cout << "5.\tRun." << endl;
 
    int menu_input;
    cin >> menu_input;

    switch (menu_input) {
        case 1: {
            
            cout << "1.\tLight Attack." << endl;
            cout << "\t\tDeals 5 points of damage. No Stamina cost." << endl << endl;
            cout << "2.\tHeavy Attack" << endl;
            cout << "\t\tDeals 20 points of damage. Stamina Cost of 10 points." << endl << endl;
            
            int att_input;
            cin >> att_input;
            
            switch (att_input) {

                case 1: {

                    cout << "You dealt 5 points of damage!" << endl << endl;
                    ogreHP= - 5;
            
                    break;
                }
                case 2: {

                    cout << "You dealt 20 points of damage!" << endl << endl;
                    Stamina= - 10;
                    ogreHP= - 20;

                    break;
                }

提前致谢!

【问题讨论】:

  • 你知道调试器是什么吗?哪些值没有更新?请更具体,并尝试使用您的代码的较小示例,其中您的问题仍然存在。谢谢
  • 您的代码似乎不完整,请指定未“更新”的值。
  • 你关于减少健康和耐力的语法是错误的。您正在设置实际值而不是减少。当您想将变量减少一定数量时,请使用 -=

标签: c++ int switch-statement


【解决方案1】:

当你编写这个语法时:

Stamina = - 10;
ogreHP = - 20;

您实际上分别将-10-20 分配给StaminaogreHP,它们在这里不称为“减少”。而不是这样,如果您可以编写以下内容:

Stamina -= 10; // Stamina = Stamina - 10; -> previous - 10 = now
ogreHP -= 20;  // ogreHP = ogreHP - 20;   -> previous - 20 = now
//     ^^ is called 'assignment operator'

问题将得到解决。您在代码中的案例 1 中所做的相同操作。

【讨论】:

    猜你喜欢
    • 2021-04-02
    • 1970-01-01
    • 2022-06-19
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多