0

e can be approximated using the formula e = 1 + (1/1!) + (1/2!) + (1/3!)... + (1/n!). I am trying to use for loops to accept whatever integer the user sets n to be. The program should approximate e by using the formula above from (1/1!) + .... (1/n!) and out put the result.

The nested for loop calculates the factorial of n (tested it separately and it works) and the variable defined, frac, puts the factorial into a fraction of 1/(answer to factorial). I store the value into a variable e and it should add the new fraction to the old value every time an iteration is done. I cannot not understand what is wrong with my loops that they are not out putting the right answer.

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);

Output when I enter the integer 7 as n = 1.0001986906956286

4

1 回答 1

0

你不需要整个内循环。你只需要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。Plunker:http://plnkr.co/edit/OgXbr36dKce21urHH1Ge?p= preview

于 2018-03-12T18:24:55.287 回答