伯努利漫衍(bernoulli distribution), 是判定某件工作产生可能未产生的概率;
给定参数p, 可以修改概率的值, 产生概率(true)是p,未产生概率(false)是1-p;
随机库, 提供漫衍工具bernoulli_distribution, 输出bool值, 产生为true, 未产生为false;
伯努利漫衍, 概率为0.5时, 可以等概率输出一个二元事件, 如先后顺序;
留意: 引擎和漫衍工具, 声明在函数外, 则每次挪用, 城市发生差异的值, 但却是牢靠的, 可以利用time(0), 界说差异的引擎;
代码如下:
#include <iostream> #include <vector> #include <string> #include <random> #include <algorithm> #include <cmath> using namespace std; bool play (bool first) { std::default_random_engine e; std::bernoulli_distribution b(0.6); //得胜概率较大 bool win = b(e); if(first) //我们得胜的概率大 return win; else return !win; } int main() { std::string resp; std::default_random_engine e; std::bernoulli_distribution b; do { bool first = b(e); //伯努利出产器 std::cout << (first ? "We go first" : "You get to go first") << std::endl; //判定先后手 std::cout << ((play(first)) ? "congrats, you won" : "sorry, you lost") << std::endl; std::cout << "play again? Enter 'yes' or 'no' " << std::endl; } while (std::cin >>resp && resp[0] == 'y'); return 0; }
输出:
We go first congrats, you won play again? Enter 'yes' or 'no' yes We go first congrats, you won play again? Enter 'yes' or 'no' yes We go first congrats, you won play again? Enter 'yes' or 'no'
作者:csdn博客 Spike_King