Srand() and rand() Functions

Explain srand() and rand() Functions

Questions by shiv29

Showing Answers 1 - 3 of 3 Answers

UncaAlby

  • Apr 20th, 2010
 

rand() uses what is known as a "multiplicative congruential" method for generating pseudo-random numbers between 0 and 32767.  (The exact maximum can be system dependent.)

It will start with a system dependent default "seed" of 0, 1, or nondeterministic. Each subsequent call will return a different result which appears random. It's not really random, as the sequence is deterministic. If you restart the program, you'll get the exact same sequence.

srand() sets the "seed" to some fixed value.  This causes rand() to start in a different place in the sequence.

Set the "seed" to a specific value for deterministic testing.  You'll get the same numbers each time you run the program. Set it to something unpredictable, such as the process ID and/or time of day, when the system is ready for production and the end-user expects a "random" number.

Note that there are much better algorithms available for generating random numbers, but this makes a good start for simple games.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions