1

I want to use the int balance and cPercent and so on in both of my functions. How would I do this?

link to pastebin. And the code:

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) {

        }
    }
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
midcore
  • 5
  • 1

1 Answers1

1

You can do one of two things: make global variables or pass the variables as parameters.

To make global variables then declare the two variables outside of the two functions like so

int balance;
int cPercent;

before the definitions of both functions. Alternativel you can pass the integers as a parameters to the function that you are calling in order for it to be "in scope". If you want to use cPercent and balance in the gamble function, then you need to change it's method signature to.

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

and then when you to to call the function from the main function you need to pass them in like so:

gamble(balance, cPercent)

This causes a copy of the integers to be in scope in the gamble function.

Jon Deaton
  • 3,943
  • 6
  • 28
  • 41
  • 1
    It's best to mark answers with a checkmark if they solved your issue. That way if someone else has this issue while searching they can see this answer was resolved. Thanks – Derek Lawrence Jul 21 '17 at 20:17