[英]C# Lottery odds to win
我必须提出这个问题:“您想以一种变体参加 49 次机会中的 6 次游戏,并且您想知道您将赢得什么机会:I 类(6 个数字),II 类(5 个数字),类别 III(4 个数字)。编写一个应用程序,接收球总数、抽出的球数作为输入数据,然后在使用单一变体时以小数点后 10 位的精度打印获胜机会”。 例如 40、5 和 II(5 个数字),结果为 0.0002659542。 我知道这个公式是 n!/k!*(nk)! 但我制作的程序只适用于第一类。
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
int k = Convert.ToInt32(Console.ReadLine());
string extract = Console.ReadLine();
int category1 = category(extract);
switch (category1)
{
case 6:
calculateTheOddsToWin(n, k, extract);
break;
case 5:
calculateTheOddsToWin(n, k, extract);
break;
case 4:
calculateTheOddsToWin(n, k, extract);
break;
}
}
static void calculateTheOddsToWin(int n, int k, string extract)
{
double comb = combination(n, k);
decimal solution = (decimal)(1 / comb);
decimal round = Math.Round(solution, 10);
Console.WriteLine(round);
}
static double combination(int n, int k)
{
double factN = factorial(n);
double factK = factorial(k);
double factNK = substractFactorialNK(n, k);
double combination = factN / (factNK * factK);
return combination;
}
static double factorial(int n)
{
double factorialN = 1;
for (int i = 1; i <= n; i++)
{
factorialN *= i;
}
return factorialN;
}
static double substractFactorialNK(int n, int k)
{
double factorialNK = 1;
int substract = n - k;
for (int i = 1; i <= substract; i++)
{
factorialNK *= i;
}
return factorialNK;
}
static int category(string extract)
{
if (extract == "I")
{
return 6;
}
else if (extract == "II")
{
return 5;
}
else if (extract == "III")
{
return 4;
}
else
{
return -1;
}
}
关于如何解决这个问题的任何想法?
这是一道数学题,所以经过研究,我是这样做的: private static double Factorial(int value) { double result = 1.0;
for (int i = 2; i <= value; ++i)
result *= i;
return result;
}
static double Combinations(int x, int y)
{
return Factorial(x) / Factorial(y) / Factorial(x - y);
}
private static double Chances(int a, int t, int c)
{
return Combinations(t, t - c + 1) *
Combinations(a - t, c - 1) /
Combinations(a, t);
}
public static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int k=Convert.ToInt32(Console.ReadLine());
string category=Console.ReadLine();
if (category == "I")
{
int categoryInt = 1;
Console.WriteLine(string.Format("{0:F10}", Chances(n, k, categoryInt)));
}
if (category == "II")
{
int categoryInt = 2;
Console.WriteLine(string.Format("{0:F10}", Chances(n, k, categoryInt)));
}
if (category == "III")
{
int categoryInt = 3;
Console.WriteLine(string.Format("{0:F10}", Chances(n, k, categoryInt)));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.