我正在尝试按
计算电子邮件数量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,但是没有修复它。如何根据我上面写的公式对数字采取行动?
答案 0 :(得分:7)
你根本不需要因子(其整数除法和整数溢出问题)
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
答案 1 :(得分:1)
正如@kabdulla和@ScottChamberlain所说,你正在进行整数除法,你需要一个浮点除法:
for (int b = 1; b < i; b++) //calculates x! here.
{
factorial = factorial * b;
}
factResult = factResult + (1 / factorial);
应该是
for (int b = 2; b < i; b++) //calculates x! here.
{
factorial = factorial * b;
}
factResult = factResult + (1.0 / factorial);
另外,我在for
开始b = 2
循环,因为乘以1是没用的。