-4

Possible Duplicate:
Generate Random numbers uniformly over entire range
C++ random float

How can I generate a random number between 5 and 25 in c++ ?

#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

void main() {

    int number;
    int randomNum;

    srand(time(NULL));

    randomNum = rand();

}
Community
  • 1
  • 1
faressoft
  • 19,053
  • 44
  • 104
  • 146

4 Answers4

12

Do rand() % 20 and increment it by 5.

dlev
  • 48,024
  • 5
  • 125
  • 132
JosephH
  • 8,465
  • 4
  • 34
  • 62
  • 5
    Even though the OP's question is terribly vague (what does "random" mean?), this answer should at least mention that the resulting distribution is biased. – Kerrek SB Nov 18 '11 at 16:42
  • 1
    First of all, `rand()` is a pseudo random number generator, not a true random number generator so there's a bias right there in the first place. Secondly, you're taking a modulo of a number which has a upper bound that is not a factor of 20 ( look up `MAX_RAND` ). This can't make the output uniformly distributed. I know I should have talked about this in my answer, but looking at the quality of the question, i assumed that he didn't really need the true RNG. – JosephH Nov 19 '11 at 15:09
6

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 just as well be:

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 on the same range.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
2

The C++ way:

#include <random>

typedef std::mt19937 rng_type; // pick your favourite (i.e. 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);
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0
#include <cstdlib>
#include <time.h>

using namespace std;

void main() {

    int number;
    int randomNum;

    srand(time(NULL));

    number = rand() % 20;
cout << (number) << endl;

}
bob saget
  • 59
  • 3