1. ## Random Decimals

Hi

Ive found lots tutorials detailing how to create random integer values, but I was wondering how to create random decimal values between a range?

Thanks for any help

TJJ

2. do something like this:
Code:
`float number=(1+rand()%10000)/100.0;`
the only thing random about that code is the rand() part... take notice that in the formula 1+rand()%100;, the 1+ just adds one to whatever comes out, and the %100 is just performing a modulo on whatever rand() comes out to be...

don't forget to put this somewhere near the beginning of your program:
Code:
`srand(time(0));`

3. >float number=(1+rand()%10000)/100.0;
float number=(float)(1+rand()%10000)/100.0;

4. No you don't need that float casting there because the number he's dividing (100.0) is already a float. Well, technically its a double so you'd have to make it 100.0F.

5. (1+rand()%10000) isn't a floating point number. Usually, when performing operations on mixed types, the result is an integer value; so yes, the typecast is necessary if only to eliminate ambiguity.

6. No: only one of the operands has to be a floating point value for the result to be floating point. The (1+rand()%10000) part yields an integer but the 100.0 is a floating point value. So when you divide, the result will be a floating point value.

7. Or heck why not use the better approach of :
Code:
```float floatrandom(float lowerbound, float upperbound)
{
return ((float)rand() / RAND_MAX) * (upperbound - lowerbound) + lowerbound;
}```
The mod operator shouldn't be used for getting random numbers. For example if you wanted to get a number between 0 and 65535 but your RAND_MAX was only 32767 then using the mod operator will make us SOL. However by using the rand()/RAND_MAX method you have now extended your range to handle any number you want.

8. >>No: only one of the operands has to be a floating point value for the result to be floating point.
Since when? I'm pretty sure I recall encountering a bug caused by this, where I had one integer and one floating-point (I think I was trying to convert degrees to radians or vice versa), and the whole thing was converted to an integer and rounded down, causing some very funked out results.

I'll run a test though, maybe you're right.

**EDIT**
Grr, you're right Learn something new every day...