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 :: c++ find sum of vector 
Cpp :: reading in lines from a file to a vector c++ 
Cpp :: arduino led code 
Cpp :: qstring to char* 
Cpp :: find character in string c++ 
Cpp :: stack implementation using linked list in cpp 
Cpp :: resize two dimensional vector c++ 
Cpp :: comment in c++ 
Cpp :: helloworld in c++ 
Cpp :: spicoli 
Cpp :: removing a character from a string in c++ 
Cpp :: maximum value in map in c++ 
Cpp :: integer type validation c++ 
Cpp :: sort function from bigest to smallest c++ 
Cpp :: Unsorted Linked list in c++ 
Cpp :: c++ array loop 
Cpp :: c++ print vector without loop 
Cpp :: c++ compare time 
Cpp :: C++ switch - case - break 
Cpp :: reverse c++ 
Cpp :: convert all characters in string to uppercase c++ 
Cpp :: sleep system function linux c++ 
Cpp :: Write C++ program to sort an array in ascending order 
Cpp :: c++ init multidimensional vector 
Cpp :: C++ array sort method 
Cpp :: how to erase a certain value from a vector in C++ 
Cpp :: vector reverse function in c++ 
Cpp :: functors in c++ 
Cpp :: cout hex c++ 
Cpp :: stringstream stream number to string 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =