首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++随机数生成器,不是随机的,但总是返回相同的数字

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

Stack Overflow用户
提问于 2015-04-10 03:36:34
回答 2查看 129关注 0票数 1

嗨,我正在寻找RandNum生成一个介于2-10之间的数字,然后这个数字被从15中删除。

现在,每次执行程序时,从15 (PerseusHealth)中取走的数字是7。我如何解决这个问题,并使其成为随机的?

代码语言:javascript
复制
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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-10 03:44:12

使用srand初始化。

代码语言:javascript
复制
srand((unsigned)time(0));

此外,我认为你没有正确地把括号放在:

代码语言:javascript
复制
int randNum = (rand()%(Maxhit - Minhit)) + Minhit; 
票数 4
EN

Stack Overflow用户

发布于 2015-04-12 04:21:50

@ebad86答案顶部的澄清

  1. rand()以质量不佳而闻名,特别是在使用低比特时。例如,最有可能的情况是,输出总是以低位设置为1。简单的解决方案可能是通过移位位(例如,8位)从序列的中间使用比特。
  2. 如果rand()的最大生成输出不能被(Max点击-最小命中)整除,您将得到(稍微)有偏的结果。就你的目的而言,这是可以的,但你最好知道。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29552901

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档