Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Execute a section of code depending on a probability

If I have a probability between 0 and 1 where 1 executes every time and 0 never executes, how would I implement that into my code?

For instance, I have a probability of 0.8, how would I program a section of code to run 80% of the time.

I assume we used the rand() function but I don’t know how to implement that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think this would be an example of how to implement what you’re trying to do:

int main() {
    double probability = 0.8;
    srand(time(0));
    double randomNumber = (double) rand() / RAND_MAX;
    if (randomNumber < probability) {
        // execute code
    }
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading