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

C++随机数生成器,不是随机的,但总是返回相同的数。,c++,random,C++,Random,嗨,我在找RandNum生成一个介于2-10之间的数字,然后从15中去掉这个数字 现在,每次执行程序时,从15中减去的数字是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 ra

嗨,我在找RandNum生成一个介于2-10之间的数字,然后从15中去掉这个数字

现在,每次执行程序时,从15中减去的数字是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; 

使用srand进行初始化

srand((unsigned)time(0));
此外,我认为您没有正确地放置括号:

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

@ebad86答案上方的澄清

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

若rand的最大生成输出不能被Maxhit Minhit整除,那个么您将得到稍微有偏差的结果。就你的目的而言,这可能没问题,但你最好知道这一点


@ebad86答案上方的澄清

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

若rand的最大生成输出不能被Maxhit Minhit整除,那个么您将得到稍微有偏差的结果。就你的目的而言,这可能没问题,但你最好知道这一点


解决眼前的问题。在程序启动时只调用srand一次,通常传递当前时间,如srandtimeNULL。更好的是,切换到使用std::mt19936和std::random_设备来进行种子设定。在代码段中,您使用的是未初始化的变量scorpianchoice…并且scorpion中没有a。解决眼前的问题。在程序启动时只调用srand一次,通常传递当前时间,如srandtimeNULL。更好的是,切换到使用std::mt19936和std::random_设备来进行种子设定。在代码段中,您使用的是未初始化的变量scorpianchoice…,而scorpion中没有a。并将其设为Maxhit-Minhit@hennessyd在@ebad86答案的基础上,还有两个问题和抽样质量更相关。一个是由于兰德的低位有偏。另一个是由于使用%而产生的偏差,并使其最大化-Minhit@hennessyd在@ebad86答案的基础上,还有两个问题和抽样质量更相关。一个是由于兰德的低位有偏。另一个是由于使用%而产生的偏差。