gpt4 book ai didi

c# - 计算e数C#

转载 作者:行者123 更新时间:2023-11-30 13:54:20 25 4
gpt4 key购买 nike

我正在尝试用那个计算 e 数

e = 1 + (1/1! + 1/2! + 1/3! + ..)

用户将在该表格上选择试验次数。 form

 int trialNumber = Convert.ToInt32(Math.Round(trialNumberForm.Value, 0));
int factorial = trialNumber;
float factResult = 0;

for (int i = 1; i < trialNumber; i++)
{

for (int b = 1; b < i; b++) //calculates x! here.
{
factorial = factorial * b;


}
factResult = factResult + (1 / factorial);
}
factResult++;
MessageBox.Show(factResult.ToString());

它会计算您选择的任何数字的结果 1!我试图将变量类型从 double 更改为 float,但这并没有解决它。如何通过我上面写的公式对数字进行操作?

最佳答案

自从

  1/(n+1)! == (1/n!)/(n+1)

你可以很容易地实现e计算

  double factResult = 1; // turn double into float if you want
double item = 1; // turn double into float if you want

for (int i = 1; i < trialNumber; ++i)
factResult += (item /= i);

...

MessageBox.Show(factResult.ToString());

结果:

   trial number | e
-------------------------------
1 | 1
2 | 2
3 | 2.5
4 | 2.666666...
5 | 2.708333...
10 | 2.71828152557319
15 | 2.71828182845823
20 | 2.71828182845905

关于c# - 计算e数C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43563912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com