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?
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.
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.
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.
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 }
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 ) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With