How to create a random number from 5 to 25 in C ++

Possible duplicate:
Generate random numbers evenly throughout the range
C ++ random float

How to create a random number from 5 to 25 in C ++?

#include <iostream> #include <cstdlib> #include <time.h> using namespace std; void main() { int number; int randomNum; srand(time(NULL)); randomNum = rand(); } 
-4
c ++ random srand
source share
4 answers

Make rand() % 20 and increase it by 5.

+11
source share

In C ++ 11:

 #include <random> std::default_random_engine re; re.seed(time(NULL)); // or whatever seed std::uniform_int_distribution<int> uni(5, 25); // 5-25 *inclusive* int randomNum = uni(re); 

Or it could be like this:

 std::uniform_int_distribution<int> d5(1, 5); // 1-5 inclusive int randomNum = d5(re) + d5(re) + d5(re) + d5(re) + d5(re); 

which would give a different distribution in the same range.

+6
source share

C ++ method:

 #include <random> typedef std::mt19937 rng_type; // pick your favourite (ie this one) std::uniform_int_distribution<rng_type::result_type> udist(5, 25); rng_type rng; int main() { // seed rng first! rng_type::result_type random_number = udist(rng); } 
+2
source share
 #include <cstdlib> #include <time.h> using namespace std; void main() { int number; int randomNum; srand(time(NULL)); number = rand() % 20; cout << (number) << endl; } 
0
source share

All Articles