### Thread: generating random numbers in a range

1. #### generating random numbers in a range

now either i have misplaced my brain, or someting is odd here. to generate random numbers within a certain range, i have always done this:
Code:
` randnum = 1 + rand() % 6;`
this would generate numbers between 1 and 6, yes?

what i am doing now is generating random 1 byte hex numbers in certain ranges. for example, i want random hex values between (128 - 191) (0x80-0xbf).
so i did this:
Code:
` u_char ran = (u_char)(0x80 + rand() % 0xbf);`
this doesnt work, so after much prodding and poking i got this to work:
Code:
`u_char ax = (u_char) ( 0x80 + (0x0 + rand() % 0x3f));`
basically just generating a number between 0 and the difference between (191 - 128) and adding that to 128. why does the first method not work?
2. I think your key assumption is wrong. It returns values between 0 and target - 1. Example:

Code:
```#include <stdlib.h>
#include <stdio.h>

#define MAXRUNS 1000

int main(){
int i, data[7], randNum;

for (i=0; i<7; i++) data[i] = 0;

srand(10);/* any old seed */
for (i=0; i<MAXRUNS; i++){
randNum = rand() % 6;
data[randNum]++;
}

printf("Found this distribution of numbers:\n");
for (i=0; i<7; i++){
printf("\tdata[%d] = %d\n", i, data[i]);
}
}```
Output:

Code:
```Found this distribution of numbers:
data[0] = 153
data[1] = 143
data[2] = 181
data[3] = 174
data[4] = 175
data[5] = 174
data[6] = 0```
3. hmm, this is odd b/c i am reading out of two C++ books right now that specify the above syntax to generate a range. this simple example is to simulate rolling a die,
Code:
`roll = 1 +rand() % 6`
that is for a windows based book though, perhaps the functions are defined slightly different although that doesnt seem likely? i'll have to check the source later i guess.

edit: bah what ****ty book lol. did some googling and found this syntax over and over:
To use a non-zero baseline you can do the following to generate #'s 20-29:

random_integer = 20 + (rand()%10);
which is what i did after trying the 'book' method.
Last edited by infamous41md; August 31st, 2003 at 02:34 PM.
4. I was a dumb dumb and didn't see the '1 + rand()', so my code wasn't demoing what I thought was your problem.

Sorry.