Reputation: 3553
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?
Upvotes: 4
Views: 84183
Reputation: 908
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
Upvotes: 2
Reputation: 3389
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;
}
Upvotes: 1
Reputation: 39089
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
.
Upvotes: 0
Reputation: 363527
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.)
Upvotes: 5
Reputation: 258568
You're subject to overflow here - range*rand()
.
Just use what regular folks use: rand() % 10 + 1
.
Upvotes: 7
Reputation: 12457
If you want a random integer between lowest
and highest
, you'd better write
random_integer = lowest + rand() % range
Upvotes: 11