C++ How ToLesson 60Free preview
C++ Random Numbers
This lesson is part of C++ · All levels
Summary
C++ provides rand() of <cstdlib> to generate random numbers, but the result is only variable if the seed is started with srand(time(0)). Common formulas such as rand() % 6 + 1 yield dice 1 to 6, while std::random_device and mt19937 of <random> provide better quality random numbers for serious needs.
Key points
- Returns the nonnegative integer in the range up to RAND_MAX.
- Srand(seed) is called once at the beginning of the program with srand(time(0)).
- The range formula: rand() % n + starts to produce numbers starting at + n - 1.
- C++11 offers <random> with mt19937 and a more even uniform_int_distribution.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.