以一定概率运行代码

-4 c c++

我是C/C++的新手.我试图以一定的概率运行代码.

例如,我知道以下代码使其以1/2概率运行:

if (rand() % 2) {
    // runs 1/2 the time
}
Run Code Online (Sandbox Code Playgroud)

但我不知道让它运行1/4(25%)的最好方法.当我投入:

if (rand() % 4) {
    // runs 1/4 the time
}
Run Code Online (Sandbox Code Playgroud)

它运行的次数超过四次.我也尝试过:

if (rand() % 2) {
    // 1/2
    if (rand() % 2) {
        // 1/2 * 1/2 = 1/4
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个有效,但它似乎不是最好的方式.此外,该方法仅适用于1/4,1/8,1/16等.我不知道如何做像1/6的例子.

小智 6

你应该== 0if声明中加入.

if (rand() % 4 == 0) {
    // runs 1/4 the time
}
Run Code Online (Sandbox Code Playgroud)

rand()返回一个正整数,可能非常大.模数运算符%执行除法并给出余数.例如,如果取大数并除以4,则余数必须为0,1,2或3.它不能是其他任何东西.通过检查余数是否等于0,我们选择了四种可能情况之一.这意味着概率为25%.

您的原始代码运行得太频繁的原因是,rand() % 4在if语句中将除0之外的所有内容计为true.因此,如果余数为1,2或3,则条件运行.换句话说,您的代码运行3/4的时间.