硬币翻转C ++循环

时间:2014-07-20 05:23:00

标签: c++ loops

我正在尝试用c ++制作一个硬币鳍状肢。它的关键是让硬币“翻转”100次,并显示它的头部或尾部的次数。

例如:“硬币被翻转了100次。头部= 68尾巴= 32

到目前为止,这是我的代码:

#include <iostream>
#include <random>

int main()

{
    using namespace std;

    random_device rd;

    default_random_engine random(rd());
    uniform_int_distribution<int> uniform_dist(1, 2);

    int coin;
    int heads = 0;
    int tails = 0;

    coin = uniform_dist(random);

    cout << "I will flip this coin 100 times.";
    cout << "I will then print the results.";

    while (coin != 100)

我如何“翻转”硬币100次,我将如何为硬币制作一个循环?

2 个答案:

答案 0 :(得分:2)

不需要循环。你想要的是从二项分布中得出的随机数:

std::binomial_distribution<int> distribution(100,0.5);
int heads = distribution(random);
int tails = 100 - heads;

有关详细信息,请参阅http://www.cplusplus.com/reference/random/binomial_distribution/http://en.wikipedia.org/wiki/Binomial_distribution

答案 1 :(得分:0)

我不确定为什么循环对你来说很难,但这应该有用。

for ( int count = 0; count != 100; ++count )
{
   int coin = uniform_dist(random);
   if ( coin == 1 )
   {
      ++heads;
   }
   else
   {
      ++tails;
   }
}