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 :: vector fin element c++ 
Cpp :: find in string c++ 
Cpp :: c++ max of array 
Cpp :: cpp initialize multidimensional vector 
Cpp :: c++ vector pop_back 
Cpp :: find primes in a range in c++ 
Cpp :: C++ std::string find and replace 
Cpp :: initialize an array in c++ 
Cpp :: c++ programming language 
Cpp :: why we use iostream in C++ programming 
Cpp :: c++ tokenize string 
Cpp :: glew32.dll was not found 
Cpp :: c++ check palindrome 
Cpp :: reading file c++ 
Cpp :: how to get size of 2d vector in c++ 
Cpp :: set clear c++ 
Cpp :: c++ vector initialization 
Cpp :: cudamemcpy 
Cpp :: iterate over vector in c++ 
Cpp :: int to float c++ 
Cpp :: comparator in sort c++ 
Cpp :: pointer in return function c++ 
Cpp :: what is - in c++ 
Cpp :: card validator c++ 
Cpp :: c detect os 
Cpp :: pure virtual function in c++ 
Cpp :: how to use custom array in c++ 
Cpp :: check if a key is in map c++ 
Cpp :: transformer in nlp 
Cpp :: map in cpp 
ADD CONTENT
Topic
Content
Source link
Name
2+5 =