执行代码x%的时间

时间:2016-04-16 18:10:31

标签: 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);

鉴于我创造的每一种动物都有特定的分娩机会, 我怎样才能编写一个仅在chance_of_birth%的时间内评估为真的条件?

我知道我想使用rand(),但我以前从未像现在这样使用它。

沿着

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

1 个答案:

答案 0 :(得分:2)

c++11开始,您可以使用库<random>
在下面的示例中,我使用std::uniform_real_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';
}

现在,您可以在if statement中使用该随机浮点值,仅在条件为真时运行。

if (f <= 0.40) { ... }