samedi 16 avril 2016

C++ - Execute code x percent of the time

I have an animal that lives in a while loop for many days.

At the end of the day, there is a 40% chance she gives birth,

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);

Given that every animal I create can have a specific chance of giving birth, how can I write a condition that evaluates true only chance_of_birth percent of the time?

I know I want to use rand(), but I never used it like this before.

Along the lines of

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




Aucun commentaire:

Enregistrer un commentaire