random intger in cpp code example

Example 1: random number c++

#include <iostream> 
#include <ctime> 
#include <cstdlib>

using namespace std;

int main() 
{ 
    srand((unsigned)time(0)); 
    int random_integer; 
    int lowest=1, highest=10; 
    int range=(highest-lowest)+1; 
    for(int index=0; index<20; index++){ 
        random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0)); 
        cout << random_integer << endl; 
    } 
}

Example 2: random numbers c++

/*The problem with srand(time(NULL)) and rand() is that if you use them
in a loop it'll probably be executed during the same clock period
and therefore rand() will return the same number. To solve this
you can use the library random to help you.*/

#include <random>

std::random_device rd;
std::mt19937 e{rd()};
std::uniform_int_distribution<int> dist{1, 5}; //Limits of the interval
//Returns a random number between {1, 5} with
dist(e);

Tags:

Cpp Example