using rand()

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;
}
int randomNumber = rand() % (upper + lower);

Should be :
int randomNumber = lower + rand() % (upper - lower + 1);
Last edited on
What was my way telling the program to do?
Thank you for the help, by the way.
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.