4

This code is supposed to generate random number between 1 to 10, but it returns 1 every time.

int random_integer;
int lowest=1, highest=10;
int range=(highest-lowest)+1;
random_integer = lowest + int(range*rand()/(RAND_MAX + 1.0));
cout << random_integer << endl;

What's wrong in the code?

Bart
  • 19,692
  • 7
  • 68
  • 77
rajat
  • 3,415
  • 15
  • 56
  • 90
  • 2
    seed your random generator : srand((unsigned)time(0)); – Ram Sep 25 '12 at 10:16
  • 3
    C++11 have better [PRNG functionality](http://en.cppreference.com/w/cpp/numeric/random) built-in, including [classes](http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) to create numbers in a range. See the example in the last link. – Some programmer dude Sep 25 '12 at 10:17

6 Answers6

11

If you want a random integer between lowest and highest, you'd better write

random_integer = lowest + rand() % range
Anton Guryanov
  • 12,109
  • 1
  • 15
  • 16
7

You're subject to overflow here - range*rand().

Just use what regular folks use: rand() % 10 + 1.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
5
range * rand() / (RAND_MAX + 1.0)

does not do what you think. Introduce some parens:

range * (rand() / (RAND_MAX + 1.0))

(Note that this method gives skewed distributions, though.)

Community
  • 1
  • 1
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • what is the easiest way to get a unskewed distribution between 1-10 . – rajat Sep 25 '12 at 10:25
  • @rajat: http://eternallyconfuzzled.com/arts/jsw_art_rand.aspx (or use the [C++11](http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) or [Boost](http://www.boost.org/doc/libs/1_51_0/doc/html/boost/random/uniform_int_distribution.html) libraries) – Fred Foo Sep 25 '12 at 10:27
2

I agree with all the solution provided above .
now to get a different sequence every time you run your program you can use srand() function it will provide a seed to rand() function as follows:-

srand(time(NULL))  
random_integer = lowest + rand() % range 
BenMorel
  • 34,448
  • 50
  • 182
  • 322
birubisht
  • 890
  • 8
  • 16
1

This two are always part of my programs

float randf(float lo, float hi) {
    float random = ((float) rand()) / (float) RAND_MAX;
    float diff = hi - lo;
    float r = random * diff;
    return lo + r;
}
int randi(int lo, int hi)
{
    int n = hi - lo + 1;
    int i = rand() % n;
    if (i < 0) i = -i;
    return lo + i;
}
SteveL
  • 3,331
  • 4
  • 32
  • 57
0

You seem to assume that rand() returns a value between 0 and 1.

This is not correct, it return value between 0 and RAND_MAX.

Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130