c++ - 如何以指定的概率运行部分代码?

标签 c++ c++11 random

我有一个变量 cnt ,其值通过 if/else 检查声明如下:
如果cnt<=2 , 然后调用 func
否则如果 cnt > 2 , 然后调用 func概率为 P=3/(2*cnt) .
如何在 C++ 中实现这种基于概率的代码执行?

void func() {
    sendMsg();
}

最佳答案

使用像 std::uniform_real 这样的东西:

#include <random>

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);

void func() {
    // Probability 0.3
    if(dis(gen) < 0.3)
        sendMsg();
}

关于c++ - 如何以指定的概率运行部分代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34939569/

相关文章:

c++ - 创建基于堆的2D数组而不使用双指针语法?

C++0x 与 Qt Creator

c++ - OpenCV 旋转伪像和点重映射

c++ - OpenSSL C API : How to resume TLS connection after program exec()?

c++ - 为什么必须包含 <initializer_list> 才能使用 auto?

c++ - 查询使用随机整数作为 vector 的大小

c++ - 如何找到 C 库中使用的确切 rand()?

c# - RandomNumberGenerator 的正确使用

c++ - 如何返回3个值之间的最大值?

引用结构的c++类构造函数