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 :: c++ randomization 
Cpp :: min heap in c++ 
Cpp :: do you need inline for template in C++ 
Cpp :: c++ in linux 
Cpp :: c++ remove whitespace from string 
Cpp :: fast io c++ 
Cpp :: remove value from vector c++ 
Cpp :: c++ string to double 
Cpp :: c++ std::fmin 
Cpp :: how to make a 2d vector in c++ 
Cpp :: how to print with the bool value in cpp 
Cpp :: unclebigbay 
Cpp :: how to get double y dividing 2 integers in c++ 
Cpp :: how to play sound in c++ 
Cpp :: cannot open include file: 
Cpp :: lopping over an array c++ 
Cpp :: find length of array c++ 
Cpp :: optimized bubble sort 
Cpp :: how to traverse a linked list in c++ 
Cpp :: vector erase specific element 
Cpp :: string to number in c++ 
Cpp :: http.begin arduino not working 
Cpp :: cpp convert vector to set 
Cpp :: C++ Volume of a Sphere 
Cpp :: height of bst cpp 
Cpp :: c++ max of array 
Cpp :: how to iterate throguh a string in c++ 
Cpp :: c++ for else 
Cpp :: how to send email in c++ program 
Cpp :: upcasting in c++ 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =