Run code with certain probability
<p>I'm new to C/C++. I'm trying to make code run with a certain probability.</p>

<p>For example, I know the following code to make it run with 1/2 probability:</p>

<pre><code>if (rand() % 2) {
    // runs 1/2 the time
}
</code></pre>

<p>But I do not know the best way to make it run 1/4 (25%) of the time. When I put in:</p>

<pre><code>if (rand() % 4) {
    // runs 1/4 the time
}
</code></pre>

<p>It runs a lot more than one in four times. I also tried:</p>

<pre><code>if (rand() % 2) {
    // 1/2
    if (rand() % 2) {
        // 1/2 * 1/2 = 1/4
    }
}
</code></pre>

<p>Which works, but it doesn't seem like the best way. Also, that method will only work for 1/4, 1/8, 1/16, etc. I have no idea how to do example like 1/6.</p>