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 <&l开发者_如何转开发t; 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() % 7
will give you a value in the range [0, 6]. A dice has values in the range [1, 6], you should use 1 + rand() % 6
instead.
* Update: *
This can be done with C++ references:
int computer(int& compscore)
{
...
compscore += diceRoll;
...
}
int var = 0;
computer( var );
For this declaration, the function takes the actual variable var
as an argument, and changes done to compscore
within the function are reflected in the variable var
as compscore
and var
for that particular invocation are just aliases to the same variable.
In C the same effect is achieved with pointers:
int computer(int* compscore)
{
...
*compscore += diceRoll;
...
}
int var = 0;
computer( &var );
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.
You're cout
ing the diceRoll
here, so it's only ever going to print the current roll as opposed to the total.
Assuming you're correctly printing the dice roll, you also need to write return humanscore;
and return compscore;
at the end of those functions to pass back to the new result.
You are passing your parameters by value. This means that any changes to them are thrown away when the function is done. If you want your scores to persist you have a few choices. You could pass the parameters by reference, which in C++ could be done by passing a pointer to the score. You could make your function return the new score, and then pass the returned value to the function the next time you call it. You would also have the significantly less desirable solution of using global variables.
精彩评论