C++ 以x%的时间执行代码

C++ 以x%的时间执行代码,c++,random,C++,Random,我有一只动物,它在一个圈里生活了很多天 一天下来,她有40%的机会生孩子 class Animal { public: double chance_of_birth; ... public Animal(..., int chance) { this.chance_of_birth = chance; ... } } // create this animal Animal this_animal = new Animal(..., .50); 考虑到我

我有一只动物,它在一个圈里生活了很多天

一天下来,她有40%的机会生孩子

class Animal
{
public:
  double chance_of_birth;
  ...

  public Animal(..., int chance)
  {
    this.chance_of_birth = chance;
    ...
  }
}

// create this animal
Animal this_animal = new Animal(..., .50);
考虑到我创造的每一种动物都有特定的生育机会, 我如何编写一个只计算true的条件
出生概率
时间百分比

我知道我想使用
rand()
,但我以前从未这样使用过

沿着

if(this_animal->chance_of_birth ???)
{
  //will give birth
}

由于
c++11
可以使用库

在下面的示例中,我使用
std::uniform\u real\u distribution
生成0-1范围内的随机浮点值

#include <iostream>
#include <random>
using namespace std;

double random(int min, int max)
{ // we make the generator and distribution 'static' to keep their state
  // across calls to the function.
    std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_real_distribution<> dis(min, max);
    return dis(gen);
}

int main()
{
    double f = random(0,1); // range 0 - 1
    cout << f << '\n';
}

double rn=rand()%10000;rn/=10000.0;如果(chance>rn){/*code*/}@DarthRubik这对我帮助很大,谢谢!这会有一点偏差,因为rand返回(据称)2种可能性中的均匀分布值。有一个小疏忽:
std::mt19937
PRNG应该是
静态的
(或
thread\u local
),而不是
随机的
函数。当前,
random
不会每次返回相同的值,因为PRNG在每次调用时都使用不同的种子进行初始化。尽管如此,它还是次优的,因为它速度慢,而且不能保证
gen
的平稳运行。如果
gen
不是
static
的话,
random
的每次调用都意味着:1。调用
rd()
(一旦熵池耗尽,
random\u设备的许多实现的性能会急剧下降)2。构造一个新的(不是那么小的)
mt19937
对象。此外,通常您只为PRNG播种一次(例如)
if (f <= 0.40) { ... }