Bodor Arianna
New member
- Joined
- Feb 3, 2021
- Messages
- 2
- Programming Experience
- Beginner
I have a problem with my code.
The exercise is the following:
For example if I input:
49
6
I
The result is ok, but when I input:
45
15
III
The result is not what I expected.
It is 0.2162171866, but it has to be 0.0000001324.
Any suggestions what is wrong with my code? How can I simplify the code or correct it?
This is 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:
-at category I (6 numbers)
-at category II (5 numbers)
-at category III (4 numbers)
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.
For example if I input:
49
6
I
The result is ok, but when I input:
45
15
III
The result is not what I expected.
It is 0.2162171866, but it has to be 0.0000001324.
Any suggestions what is wrong with my code? How can I simplify the code or correct it?
This is my code :
C#:
using System;
using System.Collections.Generic;
namespace FirstApplication
{
class Program
{
public static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int k = Convert.ToInt32(Console.ReadLine());
string category = Console.ReadLine();
decimal total = 0;
switch (category)
{
case "I":
for (int z = 6; z <= 6; ++z)
total = bc(k, 6) * bc(n - k, k - 6) / bc(n, k);
decimal totalx = Convert.ToDecimal(total.ToString("0.0000000000"));
Console.WriteLine(totalx);
return;
case "II":
for (int z = 4; z <= 5; ++z)
total = bc(k, z) * bc(n - k, k - z) / bc(n, k);
decimal totalx1 = Convert.ToDecimal(total.ToString("0.0000000000"));
Console.WriteLine(totalx1);
return;
case "III":
for (int z = 4; z <= 4; ++z)
total = bc(k, z) * bc(n - k, k - z) / bc(n, k);
decimal totalx2 = Convert.ToDecimal(total.ToString("0.0000000000"));
Console.WriteLine(totalx2);
return;
}
Console.Read();
}
public static Dictionary<(int N, int K), decimal> knownValues = new Dictionary<(int N, int K), decimal>();
public static decimal 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];
}
}
}