Reputation: 15
I write a function that returns a random int
between 1 and 6. But when I call this function in main
, it gives same number. Where's the problem?
int count, diceRoll;
srand(time(NULL));
for (count = 0; count < 6; count++) {
diceRoll = (rand() % 6) + 1;
return diceRoll;
}
Upvotes: 1
Views: 71
Reputation: 144780
Your function has multiple problems:
rand()
until the time changes, which takes one full second.for
loop is useless as you always return the value of diceRoll
inside its body.You should initialize the PRNG once at the beginning of the program and use:
int rand6(void) {
return 1 + rand() % 6;
}
There is a very small bias in this function as the number of possibilities for rand()
is not a multiple of 6
.
Upvotes: 1