您的位置:首页 > 编程语言 > C#

三门概率问题之C#版

2013-11-26 13:16 399 查看

前言:

早上看到一片关于三门问题的博客/article/5699001.html,抱着该博客结论的怀疑态度用C#语言写了一些代码。实验证明该博客的结论是正确,如果变换选择选中车的概率的确是2/3.

代码:

变量声明

//总测试次数
static long AllCount = 0;
//抽到车次数
static long CarCount = 0;
protected static Random r = new Random();
//1代表羊,2代表car
static int x = 1;
static int y = 2;
static int z = 1;


方法函数

/// <summary>
/// 启动游戏
/// </summary>
/// <param name="firstChoose">第一次选择</param>
/// <param name="secondChoose">第二次选择</param>
static void gameBegin(int firstChoose,int secondChoose)
{
if (firstChoose == 1)//主持人把z打开,开始第二次选择
{
AllCount++;
switch (secondChoose)
{
//不换,依旧选择x
case 0:
break;
case 1: CarCount++;
break;
}

}
if (firstChoose == 2)//主持人把xz中其中一个打开,开始第二次选择
{
//开始选择.0为不换,1为换
AllCount++;
switch (secondChoose)
{
//不换,依旧选择y
case 0: CarCount++;
break;
case 1:
break;
}
}
if (firstChoose == 3)//选择y,主持人把x门打开,开始第二次选择
{
AllCount++;
switch (secondChoose)
{
//不换,依旧选择z
case 0:
break;
case 1: CarCount++;
break;
}

}
}


主函数

static void Main(String[] args)
{

for (int i = 0; i < 1000; i++)
{
int firstchoose = r.Next(1, 4);
gameBegin(firstchoose,1);
}
double result=(double)CarCount/AllCount;
Console.WriteLine("总共测试了{0}次,抽到车{1}次,换抽到的概率为{2}%",AllCount,CarCount,result*100);
Console.ReadKey();
}


结论:

由于一些问题不能贴图,这里直接附上结果抽了1000次,抽到车690次,抽到概率69%。有问题希望大家留言
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: