了解为什么我的 for 循环无法近似计算 e

Understanding why my for loop does not work to approximate e

e 可以使用公式 e = 1 + (1/1!) + (1/2!) + (1/3!)... + (1/n!) 进行近似计算。我正在尝试使用 for 循环来接受用户将 n 设置为的任何整数。该程序应使用上面的公式从 (1/1!) + .... (1/n!) 近似 e 并输出结果。

嵌套的 for 循环计算 n 的阶乘(单独测试它并且有效)并且定义的变量 frac 将阶乘放入 1/(阶乘的答案)的分数中。我将该值存储到变量 e 中,每次迭代完成时它都应该将新分数添加到旧值中。我无法理解我的循环有什么问题,他们没有给出正确的答案。

System.out.println("Enter an integer to show the result of 
approximating e using n number of terms.");
int n=scan.nextInt();
double e=1;
double result=1;
for(int i=1; n>=i; n=(n-1))
{
    for(int l=1; l<=n; l++)
            {
                result=result*l;
            }
    double frac=(1/result);
    e=e+frac;
}
System.out.println(e);

当我输入整数 7 作为 n = 1.0001986906956286 时的输出

您不需要整个内部循环。您只需要 result *= i.

for (int i = 1; i <= n; i++)
{
    result *= i;
    double frac = (1 / result);
    e += frac;
}

这是我刚刚拼凑的 JavaScript 版本:

function init() {
  const elem = document.getElementById('eapprox');

  let eapprox = 1;
  const n = 15;
  let frac = 1;

  for (var i = 1; i <= n; ++i) {
    frac /= i;
    eapprox += frac;
  }

  elem.textContent = eapprox;
}

这产生 2.718281828458995。笨蛋在这里:http://plnkr.co/edit/OgXbr36dKce21urHH1Ge?p=preview