C++/ python 计算硬币正面朝上的概率

207 篇文章 7 订阅
//********************************
//计算硬币正面朝上的概率
//******************************
//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 )


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值