Search
 
SCRIPT & CODE EXAMPLE
 

CPP

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

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

cpp random in range

#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 :: print float number with only four places after the decimal point in c++ 
Cpp :: c++ char to uppercase 
Cpp :: c++ functions 
Cpp :: C++ switch - case - break 
Cpp :: appending int to string in cpp 
Cpp :: factorial in c++ 
Cpp :: initialize whole array to 0 c++ 
Cpp :: map in c++ sorted descending order 
Cpp :: string length c++ 
Cpp :: data types ranges c++ 
Cpp :: insert vector to end of vector c++ 
Cpp :: number of words in c++ files 
Cpp :: convert binary string to int c++ 
Cpp :: max heap in c++ 
Cpp :: c++ simple projects 
Cpp :: max_element c++ 
Cpp :: c++ programming language 
Cpp :: restting a queue stl 
Cpp :: coordinate in 1d array c++ 
Cpp :: read and write file in c++ 
Cpp :: c++ get string between two characters 
Cpp :: c++ string to char array 
Cpp :: for c++ 
Cpp :: pascal triangle using c++ 
Cpp :: sizeof operator in c++ 
Cpp :: insert a character into a string c++ 
Cpp :: hexadecimal or binary to int c++ 
Cpp :: Find minimum maximum element CPP 
Cpp :: c detect os 
Cpp :: Disabling console exit button c++ 
ADD CONTENT
Topic
Content
Source link
Name
9+5 =