【问题标题】:How do I use the same int in different functions?如何在不同的函数中使用相同的 int?
【发布时间】:2017-12-27 20:58:54
【问题描述】:

我想在我的两个函数中使用int balancecPercent 等等。我该怎么做?

link to pastebin。和代码:

int main()
{
    int balance = 100;
    int cPercent;
    float bet;
    float thirty = 1.3;
    int outcome;
    std::cout << "Welcome!\n";
    std::cout << "\nYour balance is currently: " << balance << "$\n";
    std::cout << "Would you like to have 50% or 30% or 70% chance percent of winning?\n";
    std::cout << "Type 1 for 30%, 2 for 50% and 3 for 70%";
    std::cin >> cPercent;

    while(1){}
}

void gamble()
{
    int gPercent = (rand() % 10);
    if (cPercent = 1) {
        if (gPercent < 3) {
            outcome = floor(bet * thirty);
        }
        else if (cPercent = 2) {

        }
    }
}

【问题讨论】:

    标签: javascript needle.js


    【解决方案1】:

    您可以做以下两件事之一:创建全局变量或将变量作为参数传递。

    要创建全局变量,然后像这样在两个函数之外声明两个变量

    int balance;
    int cPercent;
    

    在两个函数的定义之前。或者,您可以将整数作为参数传递给您正在调用的函数,以使其“在范围内”。如果要在gamble函数中使用cPercentbalance,则需要将其方法签名改为。

    void gamble(int balance, int cPercent)
    {
        //definition, etc...
    }
    

    然后当你从main 函数调用函数时,你需要像这样传递它们:

    gamble(balance, cPercent)
    

    这会导致整数的副本在gamble 函数的范围内。

    【讨论】:

    • 如果他们解决了您的问题,最好用复选标记标记答案。这样,如果其他人在搜索时遇到此问题,他们可以看到此答案已解决。谢谢
    猜你喜欢
    • 2022-08-09
    • 2015-06-10
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2019-04-01
    • 1970-01-01
    • 2019-09-25
    相关资源
    最近更新 更多