Mail Archives: djgpp/1999/07/30/01:57:07
Andy Goth wrote:
> > You can use the remainder operator like this:
> >
> > number = (rand() % 101) + 1;
>
> The rand() % 101 part will return a number from 0 to 100, so if you add
> one to that you get 1 to 101. Try (rand() % 100) + 1 instead (1 to
> 100).
>
> > This will generate a number from 1 to 100. You can also substitute rand()
> > with random() which generates numbers that are more random, but random()
> > isn't as portable. Don't forget to seed it at the start of your program like
> > this:
> >
> > srand(time(0)); /* for rand() */
> > srandom(time(0)); /* for random() */
Although I agree that your method works, I also remember it earlier (months ago)
being said that the lower bits are not considered very random, and a better way is
to do something like this
number = (int)(rand() / RAND_MAX)*100+1;
or a more general formula (different for ints than floats)
for an int
int number = (int)((rand()/RAND_MAX)*(high - low + 1));
for a float
int number = (float)((rand()/RAND_MAX)*(high - low));
The above are taken from a working piece of code that utilizes a long sequence
random number generator. I have tested it before to verify that it does not go out
of bounds, simple compound if statement. Never tested it for randomness however.
Also, to correct your correction, the docs say for a range 0..N, use rand()%(n+1),
so (rand()%101)+1 is half right, just remove the +1, but keep the 101.
- Raw text -