Single Random Number in Limited Range

Started by zk52959, February 26, 2008, 09:21:36 PM

Previous topic - Next topic

zk52959

I have a situation where I need to get a random number once-only during the execution of a (very short and simple) program.  I am using the following function:


/* ============================= randTarget ================================
   This function generates a random integer between 1 and 20.
      Pre:   Nothing.
      Post:   Returns the random number target.
*/

int randTarget(void)
{
// Local Declarations
   int num;

// Statements
   srand(time(NULL));

   num = rand() % 20 + 1;   

// End function
   return num;   // Return target number
} // randTarget


My problem is that each time I run the program, and get the single random number, my random number function gives me the same few numbers over and over (e.g., 4, 8, 16, 20) and some numbers never come up.

However, if I test the random number function with a test print loop (e.g., 100 iterations) the numbers appear randomly distributed then.

How can I get a (reasonably) truly random number, on a one-time-per-program-execution basis, in a limited range of numbers (e.g., integers between 1 and 20)?

Robert

Instead of

num = rand() % 20 + 1;

use

num = (20 - 1 + 1) * (rand()/RAND_MAX) + 1

which is

num = (high - low +1) * (rand()/RAND_MAX) + 1

Robert Wishlaw

zk52959

Thank you, Robert.

When I first tried your suggestion, I kept getting "1", but when I added (float) to your code, it works perfectly.


    num = 20 * (float)rand() / RAND_MAX + 1;


Thank you again for the assistance.

severach


    num = 20.0 * rand() / RAND_MAX + 1;

Rather than cast I like to put a decimal into the number and let the compiler pick what size it's supposed to be.

zk52959