Generating a Random Integer Within a Range
Quote:
> What's the best way to generate a random integer from and including an
> integer 'from' up to and including an integer 'to'?
> The below code works unless 'from' is 0 in which case values equal to 'to'
> will never be generated.
> So what's the best/correct way to do this?
> Mike
> int
> randint(int from, int to)
> {
> float ffrom = (float)from;
> float fto = (float)to;
> return from + (int)(fto * rand() / (RAND_MAX + ffrom));
> }
You can adapt this as a function:
/* generates pseudorandom numbers
in the range: start to (range - 1) + start */
#include <stdio.h>
#include <time.h>
int main(void)
{
int x, idx, rndnum, range = 501, start = 200;
/* srand() randomizes the seed each time the program
is run, in this case with the system time */
srand((unsigned int) time(0));
/* rand() generates a pseudorandom int
in the range 0 to MAX_RAND. When used
with the % operator and the range value
it produces a result between 0 and range */
for(idx = 1; idx <= 10; idx++)
{
x = rand() % range;
rndnum = x + start;
printf("%d\n", rndnum);
}
return 0;
Quote:
}