You've over-seeded, remove the call to srand()
in diceRoll
and you should be fine (this ignores bias due to modulo usage).
Program Not Returning Results as Expected. Probably Misuse of "bool"?
質問
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;
}
解決
他のヒント
Only seed in main()
(and not in a loop) and don't seed it in the diceRoll(a)
function.
I ran it your way and got house = 2, player = 9998
.
Removing the srand((unsigned)time(null));
in the diceroll(a)
came back with:
The house has 5435 points
The player has 4565 points
I assume that is what you wanted
bool diceRoll (int a)
{
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;
}
所属していません StackOverflow