C++随机数生成器,不是随机的,但总是返回相同的数字

C++ Random number generator, isnt random but always returns the same number

本文关键字:返回 数字 随机数生成器 随机 C++      更新时间:2023-10-16

Hi-im正在查找RandNum,以生成2-10之间的数字,然后将该数字从15中去掉。

现在,每次执行程序时,从15(PerseusHealth)中减去的数字都是7。我该如何修复它,并使其随机?

void desertpath()
{
int scorpianchoice; //the option the player chooses.
int Maxhit = 10; //Max hit the scorpian can do
int Minhit = 2; //Min hit the scorpian can do
int randNum = rand()%(Maxhit + Minhit) + Minhit; 
int healthremaining = PerseusHealth - randNum; //health left in option1.

if(scorpianchoice == 1)
{
cout << "You run under the Scorpians Legs in hopes to escape " << endl;
cout << "You are hit by the scorpians Sting for " << randNum << " hp!";
cout << "You have " << healthremaining << "/15 HP Left!" << endl;
cout << "You escape the Scorpian but not without taking some damage" << endl;
}

使用srand进行初始化。

srand((unsigned)time(0));

此外,我认为你没有正确放置括号:

int randNum = (rand()%(Maxhit - Minhit)) + Minhit; 

@ebad86回答顶部的澄清

  1. rand()以质量差而闻名,尤其是在使用低位时。例如,最有可能的是,输出总是在低位设置为1的情况下生成。简单的解决方案可能是通过移位位(比如8)来使用序列中间的位

  2. 若rand()的最大生成输出不能被(Maxhit-Minhit)整除,则会得到(稍微)有偏差的结果。这对你来说可能没问题,但你最好知道它