Generating random numbers in C++ is a common task for games, simulations, and testing. The modern way uses the <random> header, which provides better distribution and control than the old C-style rand(). This guide shows you how to generate random integers and floating-point numbers, set ranges, and avoid common pitfalls.
What You’ll Need
- A C++ compiler that supports C++11 or later (most do, including GCC, Clang, and MSVC).
- A basic understanding of variables and functions.
- An editor or IDE (Visual Studio, Code::Blocks, or a simple text editor with command-line compiler).
Step-by-Step
- Include the required headers. At the top of your file, add
#include <random>and#include <iostream>for output. The<random>header provides the random number engine and distribution classes. - Create a random device (optional but recommended). The
std::random_deviceis used to seed the engine with a non-deterministic value. Write:std::random_device rd;. This gives a different sequence each run. - Choose and initialize an engine. The most common engine is
std::mt19937(Mersenne Twister). Seed it with the random device:std::mt19937 gen(rd());. If you want reproducible results, you can use a fixed number likestd::mt19937 gen(42);. - Define a distribution for integers. To get random integers between a min and max (inclusive), use
std::uniform_int_distribution<int> dist(min, max);. For example,std::uniform_int_distribution<int> dist(1, 6);for a die roll. - Generate a random integer. Call the distribution with the engine:
int random_number = dist(gen);. Each call gives a new value in the range. - For floating-point numbers, use a different distribution. Use
std::uniform_real_distribution<double> dist_real(min, max);. Note that the range is [min, max), meaning max is not included. Example:std::uniform_real_distribution<double> dist_real(0.0, 1.0);gives values from 0.0 up to but not including 1.0. - Put it all together in a complete program. Here is a full example that prints 5 random integers between 1 and 10 and 5 random doubles between 0 and 1:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> int_dist(1, 10);
std::uniform_real_distribution<double> real_dist(0.0, 1.0);
std::cout << "Random integers: ";
for (int i = 0; i < 5; ++i) {
std::cout << int_dist(gen) << " ";
}
std::cout << "\nRandom doubles: ";
for (int i = 0; i < 5; ++i) {
std::cout << real_dist(gen) << " ";
}
std::cout << "\n";
return 0;
}
Compile and run. You should see different numbers each run (unless you use a fixed seed).
Common Mistakes
- Using
rand()andsrand(). These are from C and have poor randomness and distribution. Prefer<random>. - Re-seeding inside a loop. Seeding the engine each time you need a number can produce repeats or poor sequences. Seed once at the start.
- Using modulo to limit range. For example,
rand() % 100introduces bias. Use a distribution instead. - Forgetting that
uniform_real_distributionexcludes the max. If you need max inclusive, add a small epsilon or use a different approach. - Using
std::random_devicefor all random numbers. It can be slow and may not be truly random on some implementations; use it only for seeding.
Tips
- For reproducible results (e.g., debugging), use a fixed seed:
std::mt19937 gen(12345);. - If you need many random numbers, create the engine and distribution once and reuse them.
- For different distributions (e.g., normal, Poisson), use
std::normal_distributionorstd::poisson_distribution. - Use
autoto simplify type declarations:auto dist = std::uniform_int_distribution<int>(1, 6);. - For thread safety, each thread should have its own engine instance.
Troubleshooting
- Compiler error: ‘random’ file not found. You are likely using an older C++ standard. Ensure your compiler is set to C++11 or later (e.g., use
-std=c++11with GCC). - Getting the same numbers every run. This happens if you use a fixed seed or if
std::random_deviceis deterministic on your system. Try using a different seed, or combine withstd::chrono::system_clock::now().time_since_epoch().count()as a seed. - Numbers are always the same in a loop. Make sure you are not re-creating the engine or distribution inside the loop. Create them once before the loop.
- Floating-point range seems wrong. Remember that
uniform_real_distributionis [min, max). If you need max inclusive, usestd::nextafter(max, std::numeric_limits<double>::max())as the max. - Random device throws an exception. Some systems (e.g., MinGW) have a broken
random_device. Use a fallback likestd::mt19937 gen(std::chrono::system_clock::now().time_since_epoch().count());.
Frequently Asked Questions
- Why should I use
<random>instead ofrand()?<random>provides better randomness, more control over distribution, and avoids the bias and short periods ofrand(). - How do I generate a random number between 0 and 1? Use
std::uniform_real_distribution<double> dist(0.0, 1.0);and calldist(gen). The result is in [0, 1). - Can I generate a random boolean? Yes, use
std::uniform_int_distribution<int> dist(0, 1);and treat 0 as false, 1 as true, or usestd::bernoulli_distribution. - How do I get a random number from a normal distribution? Use
std::normal_distribution<double> dist(mean, stddev);and calldist(gen). - Is
std::random_devicetruly random? It depends on the implementation. On many systems it uses hardware entropy, but on some it may be a pseudo-random generator. For most purposes, it’s fine for seeding. - Can I save the state of the engine to continue later? Yes, you can serialize the engine’s state using
operator<<andoperator>>on the engine object.
Related
- Computer Data Entry Operator Resume: Full Guide
- Changing Windows Shortcut: How to Remap Keys
- Data Entry Software for Smart Contracts: A Practical Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Insert a Zigzag Line in Word: Steps and FormattingTo insert a zigzag line in Microsoft Word, go to Insert > Shapes, choose Freeform: Shape in the…
- Timesheet Template in Word: Create and Use OneA timesheet template in Word is a document with a table for recording work dates, start and end…
- How to Get Back a Corrupted Excel File Without Losing DataTo get back a corrupted Excel file, first make a copy of it, then try Excel for Microsoft…
- How to Import CSV to Excel: Steps and Common FixesTo import a CSV into Excel for Microsoft 365 on Windows, open a workbook, select Data > From…
- PowerPoint Timeline: How to Make One That Looks PolishedTo make a polished timeline in PowerPoint, add a SmartArt timeline, enter milestones in date order, and refine…
- How to Remove Prior Formatting in Microsoft Word EasilyTo remove prior formatting in Word, select the affected text, then choose Home > Font > Clear All…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.