Archived

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

Generating a random number between x and y

This topic is 5534 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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
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