1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
int randomGen(int numOutOf)
{
return (1+ rand() % numOutOf);
}
int main()
{
srand(time(NULL));
int num;
num = randomGen(3);
cout << num << endl;
return 0;
}
|
// will be between 1 and 3 |
The second example say for instance min is 10 and max is 47.
1 2 3 4 5
|
int randomGen(int start, int end)
{
return (rand() % (end - start) + start);
}
// edit the above doesn't need the +1
|
1 2 3 4
|
int randomGen(int start, int end)
{
return (1+ rand() % (47 - 10 = 37) + 10);
}
|
so assuming that: rand() % 37 will give us a number between 0 and 36, we have the +1, to make it between 1 and 37. Then we also add on the +10(start) so in the case of 0, it will be 10?. Actually 11, I just realized my math was off by the +1, in the case of 7 will be 18, in the case of 22 will be 34, and the case of 37(max) will be 48.
get rid of the +1 at the start, this will solve this. However for numbers 1-3
as it looks like this.
1 2 3 4
|
int randomGen(int start, int end)
{
return (rand() % (3(end) - 1(start) = 2) + 1);
}
|
so rand() % 2 will give numbers between 0 and 1, which is not what we want, we want 0 and 2.
Use the first example for numbers close together such as this.
for large range numbers however the second example is good.
Edit: ALSO DON'T FORGET, you still need to seed pseudo random number using srand and time.
srand(time(NULL)); somewhere at the start of your program, but not in the random function.