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.
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.
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