The short answer
To use rand() in C++, include <cstdlib> and call std::rand(). It returns an int from 0 up to RAND_MAX. To fit the result into a range you need, take the remainder with % and add the lowest value you want.
A first example
#include <cstdlib>
#include <iostream>
int main() {
for (int i = 0; i < 5; ++i) {
std::cout << std::rand() << '\n';
}
}
Each run prints five large whole numbers. On most systems they are the same every run, because nothing has set the seed. The upper limit is RAND_MAX, which the C standard says is at least 32767 and which differs by system.
Limit the result to a range
Use this formula to get whole numbers from low to high:
#include <cstdlib>
#include <iostream>
int main() {
int low = 10;
int high = 20;
int value = low + std::rand() % (high - low + 1); // 10 through 20
std::cout << value << '\n';
}
The % (high - low + 1) part gives 0 through 10 here, and adding low shifts that to 10 through 20. The bias described in how to generate random numbers in c applies to this too, and it is larger for wide ranges.
Get a decimal number
Divide by RAND_MAX + 1.0 rather than RAND_MAX, so the result stays below 1.0:
double x = static_cast<double>(std::rand()) / (RAND_MAX + 1.0); // 0.0 or more, below 1.0
Dividing by RAND_MAX alone can return exactly 1.0.
A dice roller
#include <cstdlib>
#include <ctime>
#include <iostream>
int main() {
std::srand(static_cast<unsigned int>(std::time(nullptr))); // seed once
int roll = std::rand() % 6 + 1;
std::cout << "You rolled a " << roll << '\n';
}
Seeding is covered in more detail in how to use rand() and srand() in C.
Limits to know
rand()keeps one hidden state for the whole program, so it is a poor fit for several threads that each need their own sequence.- Its quality depends on the system, and it is not safe for passwords or other secrets. For why, see is rand() actually random.
- The remainder trick has the bias described above.
- For new code, the
<random>header has better tools. See how to generate random numbers in c.
Summary
Use std::rand() % n for a quick range, add an offset for a range that starts higher, and divide by RAND_MAX + 1.0 for decimals. For anything that needs better quality, move to <random>.