user7777
user7777

Reputation: 15

Write a function that returns random int

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

Answers (1)

chqrlie
chqrlie

Reputation: 144780

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 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

Related Questions