using rand()

Oct 12, 2016 at 2:14am
I am trying to generate a random number from a user inputted range. I am having problems with it going out of bounds. Here is my function. What am I doing wrong?

int randomInteger(int upper, int lower)
{
srand(time(0));
int randomNumber = rand() % (upper + lower);
return randomNumber;
}
Oct 12, 2016 at 2:19am
int randomNumber = rand() % (upper + lower);

Should be :
int randomNumber = lower + rand() % (upper - lower + 1);
Last edited on Oct 12, 2016 at 2:20am
Oct 12, 2016 at 2:29am
What was my way telling the program to do?
Oct 12, 2016 at 2:30am
Thank you for the help, by the way.
Oct 12, 2016 at 3:32am
Your way was telling the program to generate a random number between 0 and (upper + lower - 1).

Also, you should only call srand ONCE; normally, do it at the start of main. Otherwise you'll just get the same numbers within each program run (unless each call is further apart than a second).
Topic archived. No new replies allowed.