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