5.6 — Random numbers
Read one box at a time. No rush.
Making random numbers#
Games need dice rolls, card shuffles and surprises. Modern C++ uses <random>:
C++▶ Run
#include <iostream>#include <random> int main(){ std::mt19937 rng { std::random_device{}() }; // the random engine std::uniform_int_distribution<int> die { 1, 6 }; // numbers 1 to 6 for (int i { 0 }; i < 5; ++i) { std::cout << die(rng) << ' '; } return 0;}Output
4 1 6 6 2(Your numbers will be different every time.)
The parts#
std::mt19937 rng { ... }= a random number engine. Make it once.std::random_device{}()= a random starting point (called a seed), so each run is different.uniform_int_distribution<int> die { 1, 6 }= "give me whole numbers from 1 to 6, all equally likely".die(rng)= roll once.
Good habit
Make the engine once at the start, then use it many times. Do not make a new engine for every roll.
Project: guess the number#
C++▶ Run
#include <iostream>#include <random> int main(){ std::mt19937 rng { std::random_device{}() }; std::uniform_int_distribution<int> pick { 1, 100 }; int secret { pick(rng) }; std::cout << "I'm thinking of a number from 1 to 100.\n"; int tries { 0 }; while (true) { std::cout << "Your guess: "; int guess {}; std::cin >> guess; ++tries; if (guess < secret) { std::cout << "Too low!\n"; } else if (guess > secret) { std::cout << "Too high!\n"; } else { std::cout << "Correct! You got it in " << tries << " tries.\n"; break; } } return 0;}Tip
Try adding a limit of 7 guesses. Or ask "Play again?" at the end with a do-while.
Tip: press ← / → to move between lessons, / to search.