random int cpp code example

Example 1: c++ random

#include <cstdlib>
#include <iostream>
#include <ctime>
 
int main() 
{
    std::srand(std::time(nullptr)); // use current time as seed for random generator
    int random_variable = std::rand();
    std::cout << "Random value on [0 " << RAND_MAX << "]: " 
              << random_variable << '\n';
}

Example 2: random in c++

#include <iostream>
#include <stdlib.h>     
#include <time.h> 
using namespace std;

int main()
{
	int num;
	srand(time(0));
		num = rand() % 10 + 1;
		cout << num << endl;
}

Example 3: 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 4: cpp random int

v1 = rand() % 100;         // v1 in the range 0 to 99
v2 = rand() % 100 + 1;     // v2 in the range 1 to 100
v3 = rand() % 30 + 1985;   // v3 in the range 1985-2014

Example 5: 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);

Example 6: c++ random int troll

#include <ctime>
#define true time(NULL) % 100 != 0

Tags:

Cpp Example