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 :: max three values c++ 
Cpp :: c++ stream string into fiel 
Cpp :: c++ read file to char buffer 
Cpp :: sort in descending order c++ stl 
Cpp :: qt float to qstring 
Cpp :: if not defined c++ 
Cpp :: delete specific vector element c++ 
Cpp :: how to convert a string to a double c++ 
Cpp :: print vector 
Cpp :: c++ get last character of string 
Cpp :: convert vector into array c++ 
Cpp :: Write C++ program to copy one string to another string using pointers 
Cpp :: comment in c++ 
Cpp :: float max value c++ 
Cpp :: OPA in expanse 
Cpp :: iterating string in cpp 
Cpp :: bit c++ 
Cpp :: c++ lock 
Cpp :: run c++ file putty 
Cpp :: how to compare lower case character to uppercase cpp 
Cpp :: difference between lower and upper bound 
Cpp :: http.begin not working 
Cpp :: c++ sort vector 
Cpp :: iteraate through a vector 
Cpp :: resize 2d vector c++ 
Cpp :: how to get an element in a list c++ 
Cpp :: vector search by element 
Cpp :: aray of functions in c++ 
Cpp :: c++ vector move element to front 
Cpp :: string.begin() c++ 
ADD CONTENT
Topic
Content
Source link
Name
1+2 =