Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ how to generate a random number in a range

min + ( std::rand() % ( max - min + 1 ) )
Comment

Random in range C++

#include <iostream>
#include <cstdlib>  //required for rand(), srand()
#include <ctime>    //required for time()
using namespace std;

int main() {
    srand(time(0));     //randomizing results... (using time as an input)
    
    const int totalNumbersGenerated = 30;
    const int minRange = 1, maxRange = 20;

    cout<<"
Printing "<<totalNumbersGenerated<<" random integer numbers (from "<<minRange<<" to "<<maxRange<<"):
";
    
    for(int i=1;i<=totalNumbersGenerated;i++){
        //generating random number in specified range (inclusive)
        cout<<1+((rand () % maxRange) + minRange - 1)<<" ";
    }
    
    cout<<endl;
    return 0;
}
Comment

cpp random number in range

int range = max - min + 1;
int num = rand() % range + min;
Comment

random number in a range c++

int random(int min, int max) {
    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
    uniform_int_distribution<int> gen(min, max);
    int a = gen(rng);
    return a;
}
Comment

c++ random number within range

#include <iostream>
#include <random>
int main()
{
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 gen(rd()); // seed the generator
    std::uniform_int_distribution<> distr(25, 63); // define the range

    for(int n=0; n<40; ++n)
        std::cout << distr(gen) << ' '; // generate numbers
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: nth permutation c++ stl 
Cpp :: Plus (programming language) 
Cpp :: how to create a pair of double quotes in c++ 
Cpp :: basic symbol meanings in c++ 
Cpp :: how to sort a 2d array in c++ 
Cpp :: c++ files 
Cpp :: c++ save typeid 
Cpp :: cuda kernel extern shared memory 
Cpp :: integer to string c++ 
Cpp :: did greeks write c++ codes? 
Cpp :: prints all the keys and values in a map c++ 
Cpp :: rotate in cpp 
Cpp :: cpp random in range 
Cpp :: initialize 2d vector of ints c++ 
Cpp :: taking input from user in array in c++ 
Cpp :: prime number program in c 
Cpp :: Vector2 c++ 
Cpp :: how to free the vector c++ 
Cpp :: c++ print to standard error 
Cpp :: fork was not declared in this scope 
Cpp :: loop through char in string c++ 
Cpp :: in c++ ++ how to write if without if 
Cpp :: qt popup window 
Cpp :: c++ merge sort 
Cpp :: maximum int c++ 
Cpp :: cpp list 
Cpp :: c++ vector average 
Cpp :: c++ nagetive to positive numbers 
Cpp :: min heap and max heap using priority queue 
Cpp :: c++ typing animation 
ADD CONTENT
Topic
Content
Source link
Name
5+2 =