Archived

This topic is now archived and is closed to further replies.

Iron Eye

Generating a random number between x and y

Recommended Posts

Iron Eye    122
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"<

Share this post


Link to post
Share on other sites
the Chef    122
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]

Share this post


Link to post
Share on other sites
Iron Eye    122
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?

Share this post


Link to post
Share on other sites
origil    134
I believe the call to srand(time(NULL)) should be made outside of the function and only once, at the begining of the program.

Share this post


Link to post
Share on other sites