I have two functions where I’m adding random numbers to the total value.
The problem is that every time I call the function and print the total, it does not add. If it generates 2 it will say the total is 2. After that if I call it again and it generates 5, it says the total is 5, and doesn’t add (it should be 7 if this happened.)
Everything looks fine here…
int human(int humanscore)
{
int diceRoll= rand() % 7;
cout << "player rolled: ";
humanscore+= diceRoll;
cout << diceRoll;
cout << "human score is: " << humanscore;
}
int computer(int compscore)
{
int diceRoll= rand() % 7;
cout << "computer rolled: ";
compscore+= diceRoll;
cout << diceRoll;
cout << "computer score is: " << compscore;
}
You are modifying the value of the internal copy of the argument passed to the functions. If you want the change to be done on the external variable, change your function definitions to take references instead:
int& score.Also note that
rand() % 7will give you a value in the range [0, 6]. A dice has values in the range [1, 6], you should use1 + rand() % 6instead.* Update: *
This can be done with C++ references:
For this declaration, the function takes the actual variable
varas an argument, and changes done tocompscorewithin the function are reflected in the variablevarascompscoreandvarfor that particular invocation are just aliases to the same variable.In C the same effect is achieved with pointers:
This invocation of the function gives it the address of the variable which should be changed. For general use, you can assume that the first implementation using references will automatically generate a solution by the compiler similar to this last snippet.