hi, i recently wrote some code for a school project and before i start this question, i am not asking you to do this for me, i have just encountered an error that i would like your advice on
anyways,
we were instructed to make a program that would simulate the dice game "pig"
what i would like to know is why my code insists on giving the player one turn,
then the computer turn, and then give the player two turns, and give the computer one turn, and then again give the player two turns, and give the computer one turn
i know my question isn't phrased the best i would really appreciate some help!
thank very much =)
while ((humanTurn(Humantotalscore) < 100) && (computerTurn(Computertotalscore) <100))
{
if ((humanTurn(Humantotalscore) >= 100) && (computerTurn(Computertotalscore) <100))
When you use the && operator, the compiler won't execute the 2nd half of the statement if the first half is false... because it knows the entire expression will be false. It's often referred to as "short circuiting"
To put it in other terms...
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// this...
if(foo && bar)
{
x();
}
// is the same as this:
if(foo)
{
if(bar)
{
x();
}
}
Notice how in the 2nd example, bar won't happen if foo is false. If bar is a function call, that means the function will never be called.
The solution is to not short circuit. Do this by moving your function calls outside of the if statement:
1 2 3 4 5 6
while ((Humantotalscore < 100) && (Computertotalscore < 100))
{
humanTurn(Humantotalscore);
computerTurn(Comptertotalscore);
if ((Humantotalscore >= 100) && (Computertotalscore <100))
On a side note: if you are passing the out of the function by reference, it doesn't make sense to return it. Likewise if you are returning it, it doesn't make sense to pass by reference. Pick one and go with it. Personally, I recommend getting rid of the pass-by-reference and just return the value:
1 2 3 4 5 6 7 8
int humanTurn(int Humantotalscore) // pass by value
{
// ... blah blah ...
}
// when you call it:
Humantotalscore = humanTurn(Humantotalscore);
The problem is not with the functions. It's with how you're calling the functions. Take a look:
if ((humanTurn(Humantotalscore) >= 100) && (computerTurn(Computertotalscore) <100))
Here, your intent is to call humanTurn and computerTurn so that each of them get a turn, right?
The problem is, only humanTurn is being called, because (humanTurn(Humantotalscore) >= 100) is coming back as false. Therefore the 2nd half of the expression:
(computerTurn(Computertotalscore) <100))
is being skipped, resulting in the computer's turn being skipped.
You're doing the same thing in your while loop condition (and that shouldn't even be calling the functions anyway).
ah, i finally worked it out thanks to your first piece of advice, thank you very much for your help, sorry i didn't understand the first time and had to ask you to explain again but i appreciate the fact that you did