How does this expression work?
Num*rand() / RAND_MAX
If, for example, I replace the number with 7.7
, it gives me values from 0.
to 7.
(double
).
How does this expression work?
Num*rand() / RAND_MAX
If, for example, I replace the number with 7.7
, it gives me values from 0.
to 7.
(double
).
The rand() function generates an integer value between 0
and RAND_MAX
. so rand()/RAND_MAX
generates real value between 0 and 1
. So in the following code we have
0 <= val <= n
where n
can be an integer or a real number.
double val = n * rand()/RAND_MAX;
Tagging onto MrGreen's answer, I have found that when n is an integer, I will get an output of 0
when using double val = n * rand()/RAND_MAX;
. However, this can be addressed by a slight addition:
double val = (double) n * rand()/RAND_MAX;