generating random values

Hello guys!!!

I'm having problems generating random values.. actually i did that with

rand() % max_number

but unfortunately i'm only generating int values... How do i generate float values????
Here is something I found after a quick search:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
double randDouble(double low, double high)
{
double temp;

/* swap low & high around if the user makes no sense */
if (low > high)
{
temp = low;
low = high;
high = temp;
}

/* calculate the random number & return it */
temp = (rand() / (static_cast<double>(RAND_MAX) + 1.0))
* (high - low) + low;
return temp;
}
I don't get that code. could you be a little bit more prescily??
The above is meant to generate a random floating point number in the range [ low... high ].

Is that what you want?
Yes that is what i need but to be honest i have no idea about static_cast<double> command

Look this is what i got.

for(i=0;i<Number_nodes;i++){
for(j=0;j<2;j++){
nodes[i][j]=(rand() % dimension);
}
}

i'm generating several integer values but i cannot generate float values!!!!
function rand returns an integer in range from 0 to RAND_MAX. to make a float from it, you have to divide it by some float (if you divide an int by another int the result will be int as well).
for example:

float r = rand()/(float)RAND_MAX;

this generates a random float value in range from 0 to 1.
(float) as well as static_cast<double> converts RAND_MAX to a float.
Topic archived. No new replies allowed.