I'm new to programming and I had to work on a program that would simulate 10,000 games of craps. I got it to calculate points for house and player just fine until I added in the function "diceRoll" where player rolls again and again until it matches the first roll or 7 (house wins). Now it gives decidedly not random results (such as the house winning 0 times out of 10,000). What did I do wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
bool diceRoll (int a)
{
srand( (unsigned)time(NULL));
int n = 0;
int b = 0;
while(n < 1) {
b = rand() % 12;
if(b == a || b == 6) n++;
}
if(b == 6) return false;
else return true;
}
int main (void)
{
srand( (unsigned)time(NULL));
int a, n, house, player, point;
house = 0;
player = 0;
point = 0;
for(n = 0; n < 10000; n++) {
a = rand() % 12;
if(a == 1 || a == 2 || a == 11) {
house++;
}
else if(a == 6 || a == 10) {
player++;
}
else {
if(diceRoll(a) == true) player++;
else house++;
}
}
printf("The house has %i points.\n", house);
printf("The player has %i points.\n", player);
return 0;
}
You've over-seeded, remove the call to srand()
in diceRoll
and you should be fine (this ignores bias due to modulo usage).