# Question with rand()

• 04-17-2006
Zero_X
Question with rand()
hey guys, im still working on that little turn based game and im trying to add random damage to it. but i think im using rand() wrong.

this is how i am calling it...

i have this function built to take arguements for the random number

Code:

```int randomNum(int x,int y) {     srand(time(0));     int random = rand();     int number = (random % y)+x;     return number; }```
and then when i call to it i use
Code:

`int damage = randomNum(20,40);`
in that spot im trying to get a random number between 20-40. but when i run my program i know i am getting a number higher than 40 sometimes...so i must be using rand() wrong. any help would be awesome! Thanks
• 04-17-2006
Daved
First, you should only call srand() once, at the beginning of your program, not every time you need a random number. Your actual problem is where you put x and y in that code. Follow the calculations by hand and you will see where you went wrong.
• 04-18-2006
Ideswa
Code:

`int random = rand() % rangenumber (+startnumber);`
example:

Code:

`rand() % 20 +20;`
will give 20-40

Edit: Oops :p :)
• 04-18-2006
laserlight
I really think you should leave out the parentheses around startnumber, Ideswa.
• 04-18-2006
jafet
Code:

`    int number = (random % (y - x))+x;`
Think a bit and you'll understand why.
• 04-18-2006
Zero_X
thanks guys, I was looking over the tutorial on this site for it and it gave the example
Code:

`random = (rand() % (max - min + 1) + min)`
and im getting all that except why we add +1. my math is not so hot, you guys know why thats needed? or is it?
• 04-18-2006
Shakti
Stick some values in there instead and you will see why.

Say we want to generate random numbers betwean 5 and 10:
random = (rand() % (10-5) + 5)
vs.
random = (rand() % (10-5+1) + 5)

First one will become this:
random = (rand() % 5 + 5)
which will generate numbers betwean (0 to 4) + 5 or 5 to 9
but we didnt want 5 to 9, we wanted 5 to 10 so...
random = (rand() % 6 + 5)
which will generate numbers betwean (0 to 5) + 5 or 5 to 10....YAY!
• 04-18-2006
Zero_X
Ah I see whats going on now, Thanks alot!