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

Rob*_*rto 3 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;
}
Run Code Online (Sandbox Code Playgroud)

kad*_*ina 6

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

static int money;
Run Code Online (Sandbox Code Playgroud)

但是你的代码的问题是你在声明后的下一个语句中赋值。所以它变成

static int money;
money = 1500;
Run Code Online (Sandbox Code Playgroud)

因此,在每次 'soldSystem' 函数调用期间,money 将被赋值为 1500。

要解决此问题,您可以将两个语句合并为一个,如下所示。

static int money = 1500;
Run Code Online (Sandbox Code Playgroud)

现在因为静态变量只会被初始化一次,所以当你第一次进入这个函数时,money 被分配了 1500。


Mar*_*n B 5

money一个静态变量。这将导致它从一次调用到下一次调用保留其值:

static int money = 100;
Run Code Online (Sandbox Code Playgroud)