三门问题 代码验证概率

方案一:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>

#define TIMES 10000000	//实验越多,频率就接近于概率 

int main()
{
	long long change=0,unchange=0,i;		
	int car, choice;	
	for (i=1; i< TIMES ;i++)	
	{ 
		car = 1 + rand() % 3;	//奖品位置随机		
		choice = 1 + rand() % 3;	//人为选择随机	
		if (car == choice)
			unchange++;		//第一次选择就中奖且没有换门的情况 
		else 
			change++;		//其他情况:就是不确定第一次是否中奖,选择换门 
	}		
	printf("没有换门:中奖次数为:%d次\n",unchange);
	printf("中奖率为:%f\n",1.0*unchange/TIMES);
	
	printf("换门后:中奖次数为:%d次\n",change);
	printf("中奖率为:%f",1.0*change/TIMES);
	
	return 0;
}

运行结果:

方案二:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>

bool xuanze(bool change);
void fun(int n,bool change);

void fun(int n,bool change)
{
	int wins=0;
	for(int i=0;i<n;i++)
	{
		if(xuanze(change))
			wins++;		
	}
	printf("中奖次数为:%d次\n",wins);
	printf("中奖率为:%f\n",1.0*wins/n);
}

bool xuanze(bool change)
{
	//srand(time(0));
	//sleep(2);
	int n1=rand()%3+1;
	//sleep(2);
	int n2=rand()%3+1;
	if(n1 != n2)
		return change ? true:false;		
	else
		return change ? false:true;
}

int main()
{
	int num=0;
	printf("请输入本次实验次数\n");	
	scanf("%d",&num);
	printf("不换门:");
	fun(num,false);
	printf("换门:");
	fun(num,true); 
	
	return 0;
} 

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不掉头发的程序猿_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值