That depends on whether you are trying to generate integers
or floats
from -1
to 36
.
~
For integers
:
1) First, generate a range from 0
to N
. From -1
to 36
(inclusive), you have 38 integers.
rand()%38; //this generates a range of integers from 0 to 37.
2) Shift the range:
rand%38 - 1; //this shifts the range of numbers to -1 to 36.
~
For floats
(or numbers with decimal points):
1) generate a "continous" range from 0
to 1
.
( 1.0*rand() )/RAND_MAX; //do not forget to convert rand() to a float so that you will not get 0 from integer division.
2) Scale the range:
37 * ( (1.0*rand() )/RAND_MAX; //this scales the range to (0, 37)
3) Shift the range:
37 * ( (1.0*rand() )/RAND_MAX - 1; //this shifts to range (-1, 36)