-
Srand () w/ range
Code:
srand(time(NULL));
range = (15-9) + 1;
printf(" %d", rand() % range + 9);
That code was for a range between 9 to 15, but I'm having problems with getting it into the negative range. The range I'm trying to get is -5 to 14.
Any help is appreciated, thank you in advance.
-
>The range I'm trying to get is -5 to 14.
Code:
srand(time(NULL));
range = (14 - -5) + 1;
printf(" %d", rand() % range - 5);
-
Do it after, since rand()'s return value is 0 to RAND_MAX.
[edit]nevermind...[/edit]
-
awesome, thanks swoopy. I wasn't sure if 14 - - 5 would work, because i would assume it be 20. but then writing out the number % 20 - 5 would work as well. Thanks!
-
I guess to generalize you could write:
Code:
num = (rand() % (upper - lower + 1)) + lower
-
-
I want to be able to expand what we're doing. how would I go about only choosing intervals randomly from the range?
So between -5 to 14 but intervals of 3. Selecting only the possibilities of :
-5, -2, 1, 4, 7, 10, 13
-
Well you've got 7 different numbers so:
Code:
num = 3 * (rand() % 7) + lower;
lower would be -5 in this case.
-
Starting from 0,
Code:
/* interval of 3 from 0 */
if(num % 3 == 0)
Now adjust for starting from -5 ;)
-