How to generate random FLOAT numbers between a specified range?

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;

but what we use for float ?
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
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


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