//********************************
//计算硬币正面朝上的概率
//******************************
//Michael Wang 20180308
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
float calcuatePossible(int m, int n)
{
srand((int)time(NULL));
float poss = 0.0;
cout << "输入投硬币的次数" << endl;
cin >> m;
for (size_t i = 0; i < m; i++)
{
//假定随机数为偶数是硬币正面向上
if (rand() % 2)
{
n++;
}
}
poss = (float)n / m;
cout << "硬币正面朝上的概率是" << poss << endl;
cout << "投硬币的总次数是" << m
<< "正面向上的次数是" << n << endl;
return poss;
}
void main()
{
int m = 0, n = 0;
float possible = 0.0;
setprecision(5);
while (possible != 0.5)
{
possible = calcuatePossible(m, n);
}
//如果获得的概率是0.5则结束游戏
cout << "this time is 0.5" << endl;
system("pause");
}
Python
import random
def calcuatePossible():
print('输入投硬币的次数')
m = input('m is ')
n = 0
for index in range(0, m+1):
if random.randint(0, 100)%2:
n += 1
poss = float(n)/m
print('总投币数是%d, 正面朝上的次数是%d, 概率是%f ' % (m, n, poss) )
return poss
possible = 0.0
while possible != 0.5:
possible = calcuatePossible()
print('this time you are right\n Possibility is %f' % possible )