[英]How to calculate the winning chance of the lottery in c#?
using System;
namespace FirstApplication
{
class Program
{
public static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int k = Convert.ToInt32(Console.ReadLine());
string category = Console.ReadLine();
double total = 0;
switch (category)
{
case "I":
total = bc(k, 6) * bc(n - k, k - 6) / bc(n, k);
Console.WriteLine("{0:F10}", total);
return;
case "II":
total = bc(k, 4) * bc(n - k, k - 4) / bc(n, k);
Console.WriteLine("{0:F10}", total);
return;
case "III":
total = bc(k, 2) * bc(n - k, k - 2) / bc(n, k);
Console.WriteLine("{0:F10}", total);
return;
}
Console.Read();
}
private static double bc(decimal n, decimal k)
{
if (k == 0 || k == n)
return 1;
return bc(n - 1, k - 1) + bc(n - 1, k);
}
}
}
I have a problem with my code.我的代码有问题。
The exercise is the following:练习如下:
You participate at the lottery 6/49 with only one winning variant(simple) and you want to know what odds of winning you have:您参加的彩票 6/49 只有一个中奖变体(简单),并且您想知道您的中奖几率:
-at category I (6 numbers) - 在 I 类(6 个数字)
-at category II (5 numbers) - 在 II 类(5 个数字)
-at category III (4 numbers) - 在 III 类(4 个数字)
Write a console app which gets from input the number of total balls, the number of extracted balls, and the category, then print the odds of winning with a precision of 10 decimals if you play with one simple variant.编写一个控制台应用程序,从输入的总球数、提取的球数和类别中获取,然后如果您使用一个简单的变体,则以小数点后 10 位的精度打印获胜几率。
For example if I input:例如,如果我输入:
49 49
6 6
I我
The result is ok, but when I input:结果还可以,但是当我输入时:
45 45
15 15
III三
I don't get any result.我没有得到任何结果。
Any suggestions what is wrong with my code?有什么建议我的代码有什么问题吗?
I don't think there's anything wrong with your code.我认为您的代码没有任何问题。 It just runs for a very long time, because you call bc
with the same values again and again.它只运行了很长时间,因为您一次又一次地使用相同的值调用bc
。 I added a dictionary to store and lookup the values already calculated:我添加了一个字典来存储和查找已经计算的值:
private static Dictionary<(int N, int K),double> knownValues = new Dictionary<(int N, int K),double>();
private static double bc(int n, int k)
{
var key = (n,k);
if (!knownValues.ContainsKey(key))
{
if (k == 0 || k == n)
{
knownValues.Add(key, 1);
}
else
{
knownvalues.Add(key, bc(n - 1, k - 1) + bc(n - 1, k));
}
}
return knownValues[key];
}
And it returns in < 6 seconds with the value 0.0364626616 for your 45,15,III input.它会在 < 6 秒内返回 45,15,III 输入的值为 0.0364626616。 Whether that is right, I don't know, but at least it terminates.这是否正确,我不知道,但至少它终止了。 Maybe your teacher wanted you to try this and learn about recursion and calculation times.也许你的老师想让你试试这个并了解递归和计算时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.