C++ Random Number

closed account (EAUX92yv)
I was wondering if there was a way to create a random number between a certain range in C++. I need to use this for a game I am building. Any help is appreciated.
both uniform_int_distribution and uniform_real_distribution take the range as the constructor arguments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 rng(rd());

    std::uniform_int_distribution<> range1(10, 15);
    for(int n = 0; n < 20; ++n)
        std::cout << range1(rng) << ' ';
    std::cout << '\n';

    std::uniform_real_distribution<> range2(1.5, 1.8);
    for(int n = 0; n < 10; ++n)
        std::cout << range2(rng) << ' ';
    std::cout << '\n';
}

online demo: http://ideone.com/z03zyF
closed account (EAUX92yv)
What does the for loop do to create a random number?
http://www.cplusplus.com/reference/cstdlib/rand/

This points you to the rand function, which is within cstdlib. Just include it, call srand(NULL) (This changes the seed so it's more random than having a constant seed, which occurs if srand() isn't used.)

Then you call rand() %(range+1) + shiftAmount (which is the lowest value possible)
Topic archived. No new replies allowed.