我有一只动物会在一段时间内生活一段时间。
在一天结束时,她有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
}
既然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
仅在条件为true时运行。
if (f <= 0.40) { ... }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句