Hello,
I'm trying to get a random number using C. I've tried using random(),
but my program keeps producing numbers that are way out of range from
the numbers I put in.
Anyone got any suggestions?
You've gotten a lot of suggestions. IMO, of what you've received so
far, Thad Smith's post is probably the most thorough and accurate. I'll
add only one detail: he alluded to code that discards values as needed
to produce a flat distribution, but didn't include such code in his
post. Here's some code to do that:
/* return a pseudo-random number between 0 and limit inclusive.
*/
int rand_lim(int limit) {
int divisor = RAND_MAX/(limit+1);
int retval;
do {
retval = rand() / divisor;
} while (retval > limit);
return retval;
}
If you want to specify both a lower and an upper limit, you can call
this specifying the difference between the two, and then add the result
to the lower limit you've specified -- I have code for that, but it's
written as a C++ function that overloads this one, so it isn't topical
here.
Also note that although this is written as a loop, you can usually
expect the loop to execute only once per function call, and chances of
it executing more than twice in a particular call are almost
astronomically remote (unless rand() has massive defects).