tags:

views:

92

answers:

3
int userHP = 100;
int enemyHP = rand() % ((userHP - 50) - (userHP - 75)) + 1;

okay, for some reason this doesnt seem to work right, im trying to get 50 -25 hp for enemys.

also id rather it be a percentage... like

int enemyHP = rand() % ((userHP / 50%) - (userHP / 75%)) + 1;

but id like to stick with integers and not mess with floats or doubles... can someone help me?

+3  A: 
int randRange(int a, int b) {return a + rand() % (1+b-a);}

Edit: Thanatos points out in the link below that this approach can give numbers with statistically poor randomness. For game purposes it will work just fine, but do not use this for scientific or cryptographic applications! (In fact don't use rand() at all, use something like a Mersenne twister.)

See: http://www.eternallyconfuzzled.com/arts/jsw_art_rand.aspx for why this may not be the best solution.
Thanatos
Right. But it's a very simple solution than will work fine for setting enemy HP in a game, and doesn't use floating point, as requested.
+3  A: 

Perform some algebra on this:

rand() % ((userHP - 50) - (userHP - 75)) + 1;

rand() % (userHP - 50 - userHP + 75) + 1;

rand() % (userHP - userHP - 50 + 75) + 1;

rand() % (-50 + 75) + 1;

...and you can quickly see what's going wrong. Why not use doubles?

Thanatos
Should be `userHP + 75` in the 2nd line though, so the size of the range is more or less OK.
Péter Török
@Peter: Fixed, thanks.
Thanatos
+2  A: 

To get a Random Number in range [ Minimum , Maximum ] inclusive:

Use this integer approximation:

int RandomNumber = Minimum + rand() % (Maximum - Minimum + 1);

And make sure that (Maximum - Minimum ) <= RAND_MAX


Or use this better floating one:

double RandomNumber = Minimum + rand() * (double)(Maximum - Minimum) / RAND_MAX;
Betamoo