In this post I’ll show you how to get random number between 1 and 10.
Before diving the example you shuld know what are srand and rand functions in C++.
rand: This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.
srand : This function sets the starting point for producing a series of pseudo-random integers. If srand()
is not called, the rand()
seed is set as if srand(1) were called at program start. Any other value for seed sets the generator to a different starting point.
C++ Random Number Between 1 and 10:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> int main() { int lowest = 1; int range = 10; int random_integer; srand(time(NULL)); random_integer = lowest + rand() % range; std::cout << "Random Number: " << random_integer; } |
Output:
1 2 3 | Random Number: 4 |