There are two ways to do this.
you could use rand, but your results will be slightly biased.
What rand()
does:
Returns a pseudo-random integral number in the range between 0 and RAND_MAX.
Example:
RandomFunction = rand() % 100; // declares a random number between 0-99
RandomFunction2 = rand() % 100 + 1; // declares a random number between 1-100
This is in the library #include <cstdlib>
You can also set the seed with
srand()
What this does is set the value of the random numbers, which will be same if the function is repeated with the same value for srand()
. This is sometimes preferred in debugging, as it makes the result clear.
Reference: www.cplusplus.com
Also here's the function for finding unbiased values,
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 10);
//This function creates a random number between 1-10 and is stored in dis(gen).
// You can change the name of dis if you like.
Example:
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);
for (int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
This will generate 10
random numbers between 1-6
. Example Reference: cppreference