Generating a random number between x and y

Started by
4 comments, last by Iron Eye 21 years, 6 months ago
Today is my second day of learning C++, but thats beside the point (just a scape goat for my crappy function). Anyway I''m writing a text rpg, I want to generate a random damage between two values I pass my calcdamage() function. What I have is horribly slow, and dosn''t even seem to do what I want. I''m just seeking advice on how this could be better written. source: int calcdamage(int x, int y) { int z; //srand(time(NULL)); debugging this //z = rand() * y / (RAND_MAX + 1); another method z = (rand() % y) + 1; while (z < x || z > y) { if (z < x) { srand(time(0)); cout<<"adding to z"< y) { srand(time(0)); cout<<"subtracting from z"<<endl; z = (rand() % y) - 1; } } return z; } Thanks for any advice, -Kris
---
ConPong _//_ Google _//_ Chaos Forge - quick and easy file hosting for developers

"Games usually keep me from making my own..."
-Me
---



find your elementat mutedfaith.com.
Advertisement
How about:
z = (rand() % (y-x+1))+x;

It should do what you want, as long as y is greater than or equal to x.

/John
/John
Maby I miunderstood, but it seems very easy....

I think this is what you are looking for:
rand() % abs(x-y); // Random number between 0 and the x-y
The abs function is located in math.h

one more thing, try putting
srand(time(0));
in your main function, that have solved ths problem for me.

No way! I will never write a profile signature!

[edited by - the Chef on October 20, 2002 5:07:43 PM]
No way! I will never write a profile signature! :p
nahhh... I thought I was the first poster
No way! I will never write a profile signature! :p
Funky your piece of code seems to do what i want, however every time i call it i get the same number, i put the way i call it in a loop, well ill just have to explain.

first i call a battle function, this calls the calcdamage funtion, then subtracts hp from the proper player based on what i pass it.

for instance battle(2, 100, 200);
would take somewhere between 100, and 200 hp off you, which I called player 2.


battle goes through two if statements to determine which player to subtract hp from

the contents of one of these would be:

herohp = herohp - calcdamage(mindamage, maxdamage)

min and max damage are variables passed to the battle function.

I''ve situated srand(time(0)); in various places, and it still return the same but still random number every time

like 192, 192... and so on another time it will be 143.

Any sugestions?
---
ConPong _//_ Google _//_ Chaos Forge - quick and easy file hosting for developers

"Games usually keep me from making my own..."
-Me
---



find your elementat mutedfaith.com.
I believe the call to srand(time(NULL)) should be made outside of the function and only once, at the begining of the program.
The Department of Next Life - Get your Next-Life Insurance here!

This topic is closed to new replies.

Advertisement