Blu*_*101 9 c# probability percentage
我有这段代码:
Random rand = new Random();
int chance = rand.Next(1, 101);
if (chance <= 25) // probability of 25%
{
Console.WriteLine("You win");
}
else
{
Console.WriteLine("You lose");
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,它真的计算出25%的获胜概率吗?这里玩家获胜的机会是25%吗?
编辑:
我刚刚写了这个:
double total = 0;
double prob = 0;
Random rnd = new Random();
for (int i = 0; i < 100; i++)
{
double chance = rnd.Next(1, 101);
if (chance <= 25) prob++;
total++;
}
Console.WriteLine(prob / total);
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)
这是非常不准确的.它从大约0.15到0.3.
但是当我做更多的检查(从(i <100)变为(i <10000))时,它会更准确.
为什么是这样?为什么100次检查不够准确?
Rot*_*tem 10
这很容易检查自己:
Random rand = new Random();
int yes = 0;
const int iterations = 10000000;
for (int i = 0; i < iterations; i++)
{
if (rand.Next(1, 101) <= 25)
{
yes++;
}
}
Console.WriteLine((float)yes/iterations);
Run Code Online (Sandbox Code Playgroud)
结果:
0.2497914
Run Code Online (Sandbox Code Playgroud)
结论:是的,是的.
编辑:只是为了好玩,LINQy版本:
Random rand = new Random();
const int iterations = 10000000;
int sum = Enumerable.Range(1, iterations)
.Count(i => rand.Next(1, 101) <= 25);
Console.WriteLine(sum / (float)iterations);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15392 次 |
| 最近记录: |