Re: rand and srand




The function rand() returns a value between 0 and RAND_MAX, not between
0 and what you pass to srand(). The latter function only sets the seed
for the random number generator (on which the next random number will be
based).

If you want to have a non-predictable sequence of random numbers, it's
often a good idea to set the seed to something that is not a literal and
will change each time the program is executed.

Additionally, if you want to generate a random number between 0 and 2000,
the code to do that uses the modulus operator, thusly:

printf("%u\n", (rand() % 2001));

For one, without the \n (newline), nothing will separate your numbers from
each other. The second part of this is the % 2001. That divides the
value from rand() by 2001, and returns the remainder - so the number can
be anything from 0 to 2000. If rand() returns 2001, the modulus makes it
0, etc.

Thanks so much for your advice. I haven't used code with modulus yet and
this is the first time I've seen it.

As for your main(), I wasn't actually aware that such code was legal C. My
guess is that it is actually void main(), because you never return a value
from it, so the exit status of your program is most likely undefined. It
is a good idea, particularly in UNIX, to declare it int, and return 0 at
the end (unless the program failed).

The C99 standard wants and int. But all the compilers I've used accept
main() and main(int argc,char *argv[]) when parameters are used. Otherwise
automatic void of course with just () as parameters. Thanks for the advice
on rand. So is there really a need to use srand ( ) ?

Bill


.



Relevant Pages

  • Re: Hunt for rand and srand implementations ;)
    ... Also I tested knoppix's rand and srand.... ... rand and srand... ... void srand(unsigned int seed); ... rand retrieves the pseudorandom numbers that are generated. ...
    (sci.crypt)
  • Re: Floating point load-store behaviour.
    ... This should be "int main". ... calling srand(), you're interfering with the generator. ... You should call srand() exactly once, ...
    (comp.lang.c)
  • Re: Hunt for rand and srand implementations ;)
    ... probably have the same srand() and randroutines... ... // IBM AIX srand and rand implementation occurding to: ... int IBM_AIX_rand ...
    (sci.crypt)
  • Re: Random string
    ... The time between a call to srand() and a subsequent ... call to rand() makes no difference whatsoever unless 1) your ... int rand_lim{ ...
    (microsoft.public.vc.mfc)
  • Re: Way for computing random primes in standard C.
    ... randomness of the numbers returned by rand? ... call to srand() were removed (perhaps with a different number of ... the randomness is in the non-perfect algorithm ... ] sequence has some internal initial values. ...
    (comp.lang.c)