rand () for c++ with variables

2019-08-16 15:33发布

问题:

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?

回答1:

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?



回答2:

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;


回答3:

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



标签: c++ srand random