我想在我的两个函数中使用 int balance
和 cPercent
等等。我该怎么做?
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
函数中使用 cPercent
和 balance
,则需要将其方法签名更改为。
void gamble(int balance, int cPercent)
{
//definition, etc...
}
然后当您从 main
函数调用该函数时,您需要像这样传递它们:
gamble(balance, cPercent)
这会导致整数的副本在 gamble
函数的范围内。
关于javascript - 如何在不同的函数中使用相同的 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45243907/