Random generator not working

1
2
3
4
5
6
    srand((unsigned)time(0));
    int random_crime;
    int lowest=1, highest=3;
    int range=(highest-lowest)+1;
    random_crime = lowest+int(range*rand()/(RAND_MAX + 1.0));
    std::cout << random_crime << std::endl;

This is a random generator I found online and modified to my needs.
It always returns the same number, 3. Any reason what might be wrong with it?
Last edited on
 
    int I = 1 + rand() % (3 - 1);

This one seems to actually work. It this a good way to do it here?
No, it still doesn't work. I have a min of 1 and a max of 3. It's always returning 2. Later I will have a higher number range, but right now I only have 3 random events until I add more.
I think maybe because it seeds srand every time ? I'm not positive but I'm pretty sure your last post about the critical strike chance function I suggested ways around this, and gave sample code.

why not just use something like this:
1
2
3
4
int randomGen(int numOutOf)
{
    return (1+ rand() % numOutOf);
}


edit: or
1
2
3
4
int randomGen(int start, int end)
{
    return (1+ rand() % (end - start) + start);
}
Last edited on
Still not working for some reason. Is it because my min is 1, and my max is 3. If that is the case then what number do I need as the maximum for it to work..I also need it to have a chance of generating any of the numbers between 1 and however many I need.
I think it's because my max is so low?
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.
Last edited on
Topic archived. No new replies allowed.