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.

So what did you expect. Have you read the documentation for srand and
rand. The former "seeds" the pseudo-random number generator implemented
as rand, to start a new sequence of PRNs.

Also when I also try
RAND_MAX with srand from time to time.

That's not a very good idea. One common method is to use the return
value of the time function as the argument to srand.

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.

Well, implicit int return has been removed from the current standard,
but you'll find that almost all compilers will still tolerate code that
uses this feature. However it's always a good programming practise to
specify the return type for all your functions. It makes for *more*
readable code, not less.

Also rand returns an int value. The correct specifier for printf is %d,
not %u.

.



Relevant Pages

  • 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)
  • 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: rand() / (RAND_MAX / N + 1)
    ... information to allow you to write a program using rand and srand. ... > srand, I know what a seed is, but it is not clear to me what I have to do. ... This equation will generate s sequence of pseudo-random numbers. ... the sequence of numbers generated by the linear congruntail method will ...
    (alt.comp.lang.learn.c-cpp)
  • Re: random number geneator
    ... srand should be ... >> only oncein a program and NEVER inside a loop. ... After calling rand() the internal seed is updated ... >> this specific sequence. ...
    (comp.lang.cpp)
  • Re: Why isnt srand working?
    ... as an argument to srand(), ... Just to give a hint what pseudo-random generator algorithms do, ... extremely simple (and extremely crappy) one: ...
    (comp.lang.cpp)