Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading