C MoreLesson 50Free preview
C Random Numbers
This lesson is part of C · All levels
Summary
The rand() function produces random numbers of randomness between 0 and RAND_MAX, whereas srand() sets the generator's seed (seed) so that the order differs each time the program is run. Without proper sun calling, the random outcome will always be the same every time the program is run. For certain ranges a modulus is used, e.g. % 6 + 1 for dice 1 to 6, although this method is slightly biased.
Key points
- Call srand((unsigned) time(NULL)) right at the beginning of the program, not inside the loop.
- Returns the nonnegative integer between 0 and RAND_MAX.
- The %n yields 0 to n-1, then adds the offset for the other range.
- Modules cause slight bias when RAND_MAX+1 is not a multiple of n.
- For cryptographic purposes, it is not secure and must be replaced by a special generator.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.