rand () for c++ with variables

2019-08-16 15:30发布

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?

标签: c++ srand random
3条回答
迷人小祖宗
2楼-- · 2019-08-16 15:45

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;
查看更多
Deceive 欺骗
3楼-- · 2019-08-16 15:50

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?

查看更多
做自己的国王
4楼-- · 2019-08-16 16:03
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.)

查看更多
登录 后发表回答