Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number c++ in some range [duplicate]

Tags:

c++

random

Possible Duplicate:
Generate Random numbers uniformly over entire range

I want to generate the random number in c++ with in some range let say i want to have number between 25 and 63.

How can I have that?

like image 230
Abdul Samad Avatar asked Sep 26 '11 19:09

Abdul Samad


People also ask

How do I generate random integers within a specific range in C?

The srand() function is used to set the starting value for the series of random integers. You can use the srand() to set the seed of the rand function to a different starting point. The parameters that are passed into the srand() function are the starting values for the rand method.

How can I generate a random number within a range but exclude some?

After generating the random number you've to put the "holes" back in the range. This can be achieved by incrementing the generated number as long as there are excluded numbers lower than or equal to the generated one. The lower exclude numbers are "holes" in the range before the generated number.

How do you generate a random number from within a range?

Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.


2 Answers

Since nobody posted the modern C++ approach yet,

#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 } 
like image 82
Cubbi Avatar answered Sep 26 '22 06:09

Cubbi


You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:

25 + ( std::rand() % ( 63 - 25 + 1 ) ) 
like image 40
K-ballo Avatar answered Sep 25 '22 06:09

K-ballo