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;
}
>Solution :
Your function has multiple problems:
- the prototype is missing
- you reinitialize the pseudo random number generator from the current time at each call, hence you get the same value for
rand()until the time changes, which takes one full second. - the
forloop is useless as you always return the value ofdiceRollinside 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.