3

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
  • 18,962
  • 7
  • 68
  • 76
rajat
  • 3,279
  • 13
  • 52
  • 89
  • 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

9

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

random_integer = lowest + rand() % range
Anton Guryanov
  • 11,329
  • 1
  • 14
  • 15
6

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

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

Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
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
  • 342,876
  • 71
  • 713
  • 819
  • 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
  • 31,815
  • 47
  • 169
  • 296
birubisht
  • 860
  • 7
  • 16
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
  • 37,451
  • 6
  • 88
  • 128
0

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,273
  • 4
  • 29
  • 54