C++ 随机数生成器,不是随机的,但总是 returns 相同的数字
C++ Random number generator, isnt random but always returns the same number
嗨,我正在寻找 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 回答的澄清
rand() 以质量差着称,尤其是在使用低位时。例如,最有可能的是,输出总是在低位设置为 1 的情况下生成。简单的解决方案可能是通过移位(例如,8)
使用序列中间的位
如果 rand() 的最大生成输出不能被 (Maxhit-Minhit) 整除,您将得到(稍微)有偏差的结果。它可能适合您的目的,但您最好知道它
嗨,我正在寻找 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 回答的澄清
rand() 以质量差着称,尤其是在使用低位时。例如,最有可能的是,输出总是在低位设置为 1 的情况下生成。简单的解决方案可能是通过移位(例如,8)
使用序列中间的位
如果 rand() 的最大生成输出不能被 (Maxhit-Minhit) 整除,您将得到(稍微)有偏差的结果。它可能适合您的目的,但您最好知道它