How to generate random FLOAT numbers between a specified range?

Oct 8, 2012 at 3:25pm
Hi guys

I'm trying to generate a random float number between 1.00 and 20.00 ,i know that for integers we use this code:

int r;
r=rand()%20+1;
cout<<r;

but what we use for float ?
Oct 8, 2012 at 3:26pm
Generate a random int between 100 and 2000 and divide it by 100.

Remember that an int divided by an int gives an int, so change it to something else before you divide it.
Last edited on Oct 8, 2012 at 3:27pm
Oct 8, 2012 at 3:32pm
Range scaling is another approach here, and is what I would generally prefer when dealing with floating points:

- rand() returns a number between [0..RAND_MAX]
- knowing that, you can scale that down to a range between [0..1] by dividing by RAND_MAX
- then you can scale up to whatever range you want by multiplying by X, giving you a range of [0..X]
- you can then offset that range by adding Y to give you [Y..X+Y]


So in your case, since you want a number between 1 and 20. Y=1, and X=19

Therefore:

 
float r = (rand() / (float)RAND_MAX * 19) + 1;
Topic archived. No new replies allowed.