C++ has a
std::rand() function from
cstdlib library that generates a random number.
For example, if we add
#include <cstdlib>, we can use the
std::cout << std::rand() << "\n";std::cout << std::rand() << "\n";std::cout << std::rand() << "\n";
It would output something like:
A lot of the times, we don’t just want any random number. Suppose We want a random number from 0-9.
int answer = std::rand() % 10;
% is the modulo symbol that returns the remainder.
Seeding the Random Number Generator
For our program to work, we need to get a different random number for each execution.
To do so, we need to add this line of code before the declaration of answer:
This sets the “seed” of the random number generator.
- Anonymous contributorAnonymous contributor3077 total contributions
- Prince2517 total contributions
- Christine_Yang269 total contributions
- garanews209 total contributions
- christian.dinh2481 total contributions