Generating random numbers in C++ is a common task for games, simulations, and testing. The modern approach uses the <random> header, which provides better distribution and control than the old rand() function. This guide shows you how to create random integers and floating-point numbers, seed the generator properly, and avoid common pitfalls. You’ll need a C++11 or later compiler (most modern ones support it).
What You’ll Need
- A C++ compiler that supports C++11 or later (e.g., GCC, Clang, MSVC).
- A text editor or IDE (Visual Studio, Code::Blocks, VS Code, etc.).
- Basic familiarity with compiling and running C++ programs.
Step-by-Step
-
Include the necessary headers.
At the top of your file, add
#include <random>for the random number facilities and#include <iostream>if you want to print results. For example:#include <random> #include <iostream> -
Create a random engine.
Choose a random number engine. The most common is
std::mt19937(Mersenne Twister). Declare it like this:std::mt19937 gen;This engine will produce a sequence of pseudo-random numbers. You can also use
std::default_random_engine, butmt19937is preferred for quality. -
Seed the engine.
Without seeding, the engine starts with the same default state every run, giving identical numbers. Seed it with a truly random value, typically from a hardware device. Use
std::random_device:std::random_device rd; std::mt19937 gen(rd());This initializes the engine with a seed from
rd(). If you want reproducible results (e.g., for debugging), you can seed with a fixed number likestd::mt19937 gen(42);. -
Define a distribution.
Engines produce raw unsigned integers, but you usually want numbers in a specific range. Use a distribution object. For integers, use
std::uniform_int_distribution. For example, to get integers between 1 and 10:std::uniform_int_distribution<int> dist(1, 10);For floating-point numbers, use
std::uniform_real_distribution:std::uniform_real_distribution<double> distReal(0.0, 1.0); -
Generate a random number.
Call the distribution with the engine as an argument. The distribution returns a random number in the specified range. For example:
int randomInt = dist(gen); double randomDouble = distReal(gen);Each call to
dist(gen)produces a new number. -
Put it all together in a complete program.
Here’s a full example that prints 5 random integers between 1 and 100:
#include <iostream> #include <random> int main() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dist(1, 100); for (int i = 0; i < 5; ++i) { std::cout << dist(gen) << " "; } std::cout << std::endl; return 0; }Compile and run it. You should see five different integers each time you run the program.
Common Mistakes
- Using
rand()andsrand()– These are legacy C functions and often produce poor-quality randomness. Stick with<random>. - Seeding inside a loop – If you create and seed the engine inside a loop, you may get the same number repeatedly, especially if the loop runs fast. Seed once before the loop.
- Using
std::random_deviceas the only engine –std::random_deviceis meant for seeding, not for generating large sequences. It may be slow or even deterministic on some platforms. - Forgetting to include
<random>– This causes a compilation error. Always include it. - Assuming
uniform_real_distributionincludes the upper bound – It generates numbers in the range [a, b), meaning b is never included. If you need b included, adjust the range or use a different approach.
Tips
- Use
autofor brevity – You can writeauto gen = std::mt19937(rd());to avoid spelling out the type. - For reproducible results – Use a fixed seed (e.g.,
std::mt19937 gen(123);) when you need to debug or compare runs. - For cryptographic security – The
<random>library is not cryptographically secure. Use a library like OpenSSL or the platform’s CSPRNG for security-sensitive applications. - Shuffle containers – Use
std::shufflefrom<algorithm>with your engine to randomly reorder elements in a vector or array. - Performance – Creating a distribution object is cheap, but creating an engine is relatively expensive. Reuse the engine across many calls.
Troubleshooting
- I get the same numbers every run. – You’re not seeding the engine properly. Make sure you use
std::random_deviceto seed, or seed with a changing value like the current time (though time-based seeds are predictable). - Compilation error: ‘random’ file not found. – Your compiler may not support C++11. Enable C++11 or later with a flag like
-std=c++11(GCC/Clang) or set the language standard in your IDE. - Numbers are not uniformly distributed. – If you use
rand() % n, you get modulo bias. Usinguniform_int_distributionavoids this. Also, ensure you’re not using a poor engine likestd::minstd_randfor critical applications. - Getting negative numbers unexpectedly. – If you use
uniform_int_distributionwith negative bounds, that’s fine. But if you usestd::mt19937directly, it returns unsigned values, which can be large. Always use a distribution. - Random device is slow or blocks. – On some systems,
std::random_devicemay block until enough entropy is available. If this is a problem, you can seed from a time-based seed, but be aware of predictability.
Frequently Asked Questions
Can I still use rand() in C++?
Yes, but it’s not recommended. rand() has poor distribution and is implementation-dependent. The <random> library is more flexible and reliable.
How do I generate a random boolean (true/false)?
Use std::uniform_int_distribution<int> dist(0, 1); and treat 1 as true, or use std::bernoulli_distribution which returns true with a given probability (default 0.5).
How do I generate a random number between 0 and 1?
Use std::uniform_real_distribution<double> dist(0.0, 1.0);. This gives a double in [0, 1).
Why do I get the same sequence if I don’t seed?
Because the engine starts with a fixed default seed. Seeding with std::random_device gives a different seed each run, producing different sequences.
Can I use random numbers in multithreaded programs?
Yes, but each thread should have its own engine and distribution to avoid data races. Sharing a single engine across threads requires synchronization, which slows things down.
How do I pick a random element from a vector?
Generate a random index with std::uniform_int_distribution<size_t> dist(0, vec.size() - 1); and then access vec[dist(gen)]. Alternatively, use std::sample from C++17.
Related
- How to Autofit Columns in Excel: 3 Quick Ways
- Random Number 1-20: How to Generate & Use It
- Rotate Text Up in Excel: 4 Easy Ways
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Word and Excel Keyboard Shortcuts: Essential Keys to KnowFor Microsoft Word and Excel on Windows, the most useful shortcuts to start with are Ctrl+C to copy,…
- Microsoft Excel Solver Add-In: Setup and How It WorksMicrosoft Excel Solver is an add-in for finding values that optimize a formula while meeting limits you specify.…
- Lock Cells in Excel for the Web: A Step-by-Step GuideTo lock cells in Excel for the web, leave the cells you want protected marked as locked, unlock…
- Excel Solver: Whole Numbers, Integers, and ConstraintsNo. In Excel, Solver can use decimal values by default; it uses whole numbers only when you add…
- How to Update a Data Validation List in Excel Step by StepTo update an Excel drop-down list, select a cell that uses it, go to Data > Data Validation,…
- Excel Shortcut to Select All Data in a Column QuicklyIn Excel for Microsoft 365 on Windows, click a cell in the column and press Ctrl+Shift+Down Arrow to…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.