For an assignment I have to create a "rock paper scissor lizard spock" game where I have to output the percentage of the winnings at the end. In the program I calculate the number of games player A and B have won including tie games, the total games played, and the win percentage of each player. All the variables are int
except for the percentage which is a double
variable type. When I calculate the percentage (games won / total games) I get a 0 as a result. Any ideas why? Sorry I could not provide any code, this is an assignment and I'm not allowed to post it anywhere online.
问题:
回答1:
Without seeing code I can't be 100% sure, but my guess is that you're dividing values like this:
int numWins = /* ... */ int numLosses = /* ... */ double ratio = numWins / numLosses; // <-- Error!
In C and C++, that last line is a logic error. Although you're storing the result as a double
, because you're dividing two int
s the division is done as integer division and then stored in a double
. C and C++ don't look at the type of the variable you're assigning to when deciding what division to use; the ratio of two int
s is always computed using integer division.
To fix this, you can add a cast:
double ratio = (double)numWins / numLosses;
This casts numWins
to a double
, which ensures that the division is done as floating-point division because at least one of the operands is a double
. That should fix your issue.
Hope this helps!
回答2:
In most programming languages, division between two integers is an integer. Thus, 5 / 10
will give 0
, as will 1 / 10
and 9 / 10
. This takes place before assignment to the result variable, so the fact that the result variable is a double
is irrelevant. You need to turn either the divisor or the dividend into a double for the floating point calculation to kick in.