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
and then when i call to it i use
int randomNum(int x,int y)
int random = rand();
int number = (random % y)+x;
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
int damage = randomNum(20,40);
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.
int random = rand() % rangenumber (+startnumber);
will give 20-40
Edit: Oops :p :)
I really think you should leave out the parentheses around startnumber, Ideswa.
Think a bit and you'll understand why.
int number = (random % (y - x))+x;
thanks guys, I was looking over the tutorial on this site for it and it gave the example
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?
random = (rand() % (max - min + 1) + min)
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)
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!
Ah I see whats going on now, Thanks alot!