[英]Calculating e number C#
我試圖計算e數
e = 1 + (1/1! + 1/2! + 1/3! + ..)
用戶將在該表單上選擇試驗次數。 形成
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
正如@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);
另外,我在b = 2
開始for
循環,因為乘以1是沒用的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.