javascript - 如何在不同的函数中使用相同的 int?

标签 javascript needle.js

我想在我的两个函数中使用 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) {

        }
    }
}

最佳答案

您可以执行以下两项操作之一:创建全局变量或将变量作为参数传递。

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

int balance;
int cPercent;

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

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

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

gamble(balance, cPercent)

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

关于javascript - 如何在不同的函数中使用相同的 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45243907/

相关文章:

javascript - 如何从 React 应用程序中的公用文件夹导入文件?

javascript - 将同步 Map 方法转换为异步特征

node.js - 在流模式下使用 needle.js 时如何获取响应 header ?

javascript - 如何使用 Needed 或请求库在 Node.js 中通过 PUT 请求上传二进制正文

javascript - 如果在 Bluebird 中失败,则处理成功的 HTTP promise

javascript - 带有 js 的多个 ul tab 元素不起作用

javascript - 在单行而不是所有行上运行 jQuery 函数?

javascript - Safari 的网站问题

Node.js 针柱未完成其工作

javascript - 如何在node.js中的get-request之后返​​回值?