Reputation: 173
I wrote this program that rolls a pair of dice 20000 times. The rules are:
Second roll rules:
At the end it calculates a percentage of games won. My problem is that I should be getting a percentage of games won around 39%-60% according to a colleagues, but every time I run the program, I get around 20% and I don't understand why. Am I doing something wrong? Can someone help me please?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
int dieOne, dieTwo, keyValue, value, wins = 0, firstWins = 0, subWins = 0, loss = 0, count=0;
double percentWin, percentFirstWins, percentSubWins;
srand(time(NULL));
do{
dieOne = rand() % 6 + 1;
dieTwo = rand() % 6 + 1;
value = dieOne + dieTwo;
count++;
if (value==7||value==11) {
firstWins++;
wins++;
}
else if (value== 2||value==3||value==12) {
loss++;
}
else {
do{
keyValue = value;
dieOne = rand() % 6 + 1;
dieTwo = rand() % 6 + 1;
value = dieOne + dieTwo;
count++;
if (value==7) {
subWins++;
wins++;
}
else if (value = keyValue) {
loss++;
}
} while ( value != 7 && value != keyValue );
}
} while (count <= 20000);
percentWin = (double) wins/count * 100;
percentFirstWins = (double) firstWins/count * 100;
percentSubWins = (double) subWins/count * 100;
printf("You won %.1lf percent of your games! \nYou won %.1lf percent of games on the first roll.\nYou won %.1lf percent of games on the second roll.\n", percentWin, percentFirstWins, percentSubWins );
system("pause");
}
There are 6 possible ways to roll a 7 and two possible ways to roll an 11.
That's a total of 8 possible ways to win on the first roll.
There are 36 (6^2) possible ways to roll the dice. This means you have an 8 in 36 chance to win on the first roll or around 22% of the time.
Moreover, we have 2 possible ways to roll a 2, and 2 possible ways to roll a 3, and 2 possible ways to roll a 12. So that means there is a 1 in 6 chance (6/36) of losing on the first roll, or about 17% of the time.
So the remaining 61% of wins and losses have to come from the second roll. Whatever the case, my program is generating a very high losing streak, whereas the programs of my colleagues seem to generate a 40-60 percent of total wins. Where am I going wrong?
Upvotes: 1
Views: 316
Reputation: 2482
This may be what's causing your problem:
else if (value = keyValue) {
You're assigning, rather than comparing. This will always evaluate to true, thus artificially inflating your losses. You should be using ==
here instead of =
.
Also, for rolls that are neither a win nor a loss, you're not incrementing either the wins
or the loss
counter for either of those, but you are adding to count
. So you're going to end up with a situation where wins + loss != count
. When you calculate the win percentage, try calculating it as wins / (loss + wins)
.
Upvotes: 1