我有一个变量 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/