random number within a range

I am trying to generate a random number between 3.0 and 3.5. The code below is returning results greater than 3.5. What am I doing wrong?

1
2
3
4
5
6
7
double bftest()
{
//between 3.0 and 3.5

double rnd = rand() % 30 + 35;
return rnd / 10;
}

I'm not sure as I've never used rand() like that:
1
2
3
srand((unsigned)time(0));
int floor = 0, ceiling = 3.5, range = (ceiling - floor);
int rnd = floor + int((range * rand()) / (RAND_MAX + 1.0));


The above is a far more robust way of doing it.

If you want them to be doubles, just remove the typecast from the declaration of rnd:
double rnd = floor + (range * rand()) / (RAND_MAX + 1.0);

Oh and your problem is probably that you aren't seeding rand():
srand((unsigned)time(0));
You only need to seed rand once, put it at the top of the function.
Last edited on
you need rand() % 5 +30 so that 30<=10rnd <=35
Thanks for the fast response. Unfortunately, I am looking to return a number to just the tenths place, 3.0, 3.1, 3.2, 3.3, 3.4, or 3.5.

Your function is returning results that increment by one each time... for example:

3.2237
3.2238
3.2239
3.2240
3.2241

and on and on.
Use float instead of double then.

Or you could typecast it like this:
float rnd = floor + float((range * rand()) / (RAND_MAX + 1.0));
Actually the cast probably isn't necessary... double is just a double-precision float.
Last edited on
csiz (32) "you need rand() % 5 +30 so that 30<=10rnd <=35"


This worked perfect for my solution.

Thanks to both of you. I appreciate it.

Sigh.

rand() % 5 yields values in the range [ 0...4 ] inclusive, so 30 + [ 0 ... 4 ] yields
values [ 30...34 ] inclusive. You want rand() % 6 + 30.

Secondly, floating point is imprecise. 0.2, for example, in binary is .100110011001100...
meaning that 0.2 cannot be accurately represented in a finite number of bits.
It appears to work for you because when you output the number, it is rounding. To
illustrate the point, run this:

1
2
3
4
5
6
7
8
9
10
11
#include <iomanip>
#include <iostream>

int main() {
   double d = 0.2;
   double sum = 0;
   for( int i = 0; i < 100; ++i ) {
      sum += d;
      std::cout << std::setprecision( 20 ) << sum << std::endl;
   }
}


So in theory it should output:
0.2
0.4
0.6
... etc ...
20.0

Note what it actually outputs.

1
2
3
4
5
float RandomFloat(float min, float max)
{
	float r = (float)rand() / (float)RAND_MAX;
	return min + r * (max - min);
}
Topic archived. No new replies allowed.