How to Make Random Numbers in C++

How-to basics · Updated November 23, 2026

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

  1. 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.
  2. Create a random device (optional but recommended). The std::random_device is used to seed the engine with a non-deterministic value. Write: std::random_device rd;. This gives a different sequence each run.
  3. 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 like std::mt19937 gen(42);.
  4. 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.
  5. Generate a random integer. Call the distribution with the engine: int random_number = dist(gen);. Each call gives a new value in the range.
  6. 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.
  7. 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() and srand(). 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() % 100 introduces bias. Use a distribution instead.
  • Forgetting that uniform_real_distribution excludes the max. If you need max inclusive, add a small epsilon or use a different approach.
  • Using std::random_device for 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_distribution or std::poisson_distribution.
  • Use auto to 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++11 with GCC).
  • Getting the same numbers every run. This happens if you use a fixed seed or if std::random_device is deterministic on your system. Try using a different seed, or combine with std::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_distribution is [min, max). If you need max inclusive, use std::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 like std::mt19937 gen(std::chrono::system_clock::now().time_since_epoch().count());.

Frequently Asked Questions

  1. Why should I use <random> instead of rand()? <random> provides better randomness, more control over distribution, and avoids the bias and short periods of rand().
  2. How do I generate a random number between 0 and 1? Use std::uniform_real_distribution<double> dist(0.0, 1.0); and call dist(gen). The result is in [0, 1).
  3. 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 use std::bernoulli_distribution.
  4. How do I get a random number from a normal distribution? Use std::normal_distribution<double> dist(mean, stddev); and call dist(gen).
  5. Is std::random_device truly 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.
  6. Can I save the state of the engine to continue later? Yes, you can serialize the engine’s state using operator<< and operator>> on the engine object.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.