【发布时间】:2016-04-16 18:10:31
【问题描述】:
我有一只动物在一个while循环中生活了很多天。
一天结束时,她有 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
}
【问题讨论】:
-
如果你想使用 rand(),它会返回一个 int,你必须这样做:
double rn = rand() % 10000; rn /= 10000.0; if (chance > rn) {/*code*/} -
@DarthRubik 这对我很有帮助,谢谢!
-
这会有一点偏差,因为 rand 从 2³¹ 的可能性中返回(据称)均匀分布的值。