Re: rand and srand



Bill Cunningham wrote:
I am stumped on this one. I tried two methods and something just doesn't seem right. I'll try my new syle.

#include <stdio.h>
#include <stdlib.h>

main() {
srand(2000); /*seed unsigned */
printf("%u",rand());
}

Now I get a number much larger than 2000. Also when I also try RAND_MAX with srand from time to time.

With main I was always told int was the default type and didn't need to be declared. Main() has always worked. I hope this code is much more readable.

Bill



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.

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

--
--Falcon Kirtaran
.



Relevant Pages

  • Re: Extremely poor performance crunching random numbers under PIV-FC5
    ... in a tiny dynamic lib. ... int fakerand{ ... rand and fake rand functions this way: ... glibc rand(), randomand random_rfunctions, or at least related ...
    (Fedora)
  • Re: Surrogate factoring works very well
    ... Factor.java I changed the return type of main to int, ... BigInteger prime1 = null; ... BigInteger composite = null; ... SecureRandom rand = new SecureRandom; ...
    (sci.crypt)
  • 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: string search?
    ... I would not recommend this one. ... Then the author goes on to assume that there is an implicit conversion between a function pointer and an int. ... x = rand() ...
    (comp.lang.c)
  • Re: derangement: code review request
    ... >Then I also don't need to declare time_t timer, ... The non-equiprobability of rand() % FAMSIZ is so insignificant that it is ... TAB character by as many spaces as needed to implement TAB stops every ...
    (comp.lang.c)