[英]Probability calculator in c#
我有一个编程问题。
我一直在尝试在 c# 中做类似概率计算器的事情,因为我需要某种类型的阶乘。 我知道如何编程阶乘,但我需要
从零到某个给定数字的所有阶乘的总和。
假设输入数字是某个常数r
,我想要的是:
0! + 1! +2! + ... + (r-1)! + r!
这是我到目前为止所得到的,但仍然无法正常工作:
double a, j, k = 1, sum = 1, l = 1;
for (a = 1; a <= f; a ++)
{
for (j = 1; j <= a; j++)
{
l = k * j;
}
sum = sum + l;
}
Console.WriteLine(sum);
一个简单for
循环就足够了。 由于factorial
增长很快,我们使用BigInteger
类型; 但是,如果您愿意,可以将所有BigInteger
更改为double
:
using System.Numerics;
...
// 0! + 1! + 2! + ... + value!
public static BigInteger MyFunc(int value) {
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
BigInteger result = 1;
BigInteger factorial = 1;
for (int i = 1; i <= value; ++i)
result += (factorial *= i);
return result;
}
演示:
using System.Linq;
...
int[] tests = new int[] {
0, 1, 2, 3, 4, 5, 6, 7
};
string report = string.Join(Environment.NewLine,
tests.Select(x => $"{x} => {MyFunc(x),4}"));
Console.WriteLine(report);
结果:
0 => 1
1 => 2
2 => 4
3 => 10
4 => 34
5 => 154
6 => 874
7 => 5914
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.