c++ - 多次调用一个函数,但使用上次存储的变量值

标签 c++

我试图制作一个小游戏,你可以选择种植什么,并有一个金钱系统。
我创建了函数 soldSystem其中我使用 switch 来确定植物类型以及每种植物的成本。而在 main我打印了关于植物的信息,如果我已经打印了钱。它不像我想要的那样工作。一个例子:我有 100 美元,我种了 50 美元,当我卖掉它时,我有 150 美元,但是当我种植另一件事时,它又从 100 美元开始。


int soldSystem(int moneyNum) {
    int money;
    money = 100;
    int i;
    i = 1;
    while (i < 2) {
        switch (moneyNum)
        {
        case 0: {
            if (money >= 50) {
                cout << "Tomatoes planted\n";
                money = money - 50;
                cout << "You have :" << money << " Dollars" << endl;
                cout << "\n";
                cout << "Tomatoes Sold\n";
                money = money + 100;
            }
            else cout << "Don't have enough money\n";
        }


                break;
        case 1: {
            if (money >= 100) {
                cout << "Carrots planted";
                money = money - 100;
                cout << "You have:" << money << " Dollars" << endl;
                cout << "\n";
                cout << "Carrots Sold\n";
                money = money + 300;
            }
            else cout << "Don't have enough money\n";
        }


                break;
        case 2: {
            if (money >= 300) {
                cout << "Mushrooms planted\n";
                money = money - 500;
                cout << "You have:" << money << " Dollars" << endl;
                cout << "\n";
                cout << "Mushrooms Sold\n";
                money = money + 1000;
            }
            else cout << "Don't have enough money\n";
        }


                break;


        default:
            cout << "Try again\n";
            money = money;
            break;
        }
        i++;
        

    }


    return money;
}


int main()
{
    int i,playerChoose;
    i = 1;
    while (i > 0) {
        cout << "Choose what to plant\n";
        cout << "0-Tomatoes(50/100);1-Carrots(100/300);2-Mushrooms(500/1000)\n";
        cin >> playerChoose;
        if (-1 < playerChoose < 3) {
            cout << "You have:" << soldSystem(playerChoose) << endl;
            cout << "\n";
            
        }
    }
    cout <<"You have:"<<soldSystem << endl;
    
    return 0;
}

最佳答案

如果需要保留函数调用之间的值,则需要使用静态存储类。静态变量只会被初始化一次。您可以在函数内部声明如下所示的“money”变量。

static int money;
但是你的代码的问题是你在声明后的下一个语句中赋值。所以它变成
static int money;
money = 1500;
因此,在每次 'soldSystem' 函数调用期间,money 将被赋值为 1500。
要解决此问题,您可以将两个语句合并为一个,如下所示。
static int money = 1500;
现在因为静态变量只会被初始化一次,所以当你第一次进入这个函数时,money 被分配了 1500。

关于c++ - 多次调用一个函数,但使用上次存储的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64865687/

相关文章:

c++ - Python中是否有类似于C++ STL map的结构?

c++:私有(private)构造函数意味着没有在标题中定义该类对象?

c++ - 将 LibTiff 安装到 Visual Studio 2010

java - 从 C++ 切换到 Java : What are the key points?

c++ - 如何访问类的静态成员?

c++ - 解析文件中的数据并存储在对象中

c# - 混合程序集未发现 native DLL

android - 我应该为我的库和应用程序使用什么编译器标志以获得最佳性能 NDK (CMake)

c++ - 如何删除对象之间的变量共享?

c++ - 确保 vector 中的共享指针被正确推回