rand () for c++ with variables

家住魔仙堡 提交于 2019-12-25 04:53:21

问题


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



来源:https://stackoverflow.com/questions/2982369/rand-for-c-with-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!