I'm trying to get a factorial using a for loop; but I'm doing something wrong

Viewed 66

Deepest apologies as I'm sure I'm being dumb but I haven't been able to crack this and I have a school deadline coming up :(

this chunk of code is supposed to approximate the number e, by repeating this process:
e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! + ...
the user is supposed to specify the amount of iterations with the int e_stop, so that the output would look like this:
1 -> 2 2 -> 2.5 3 -> 2.666.. 4 -> 2.708333..
and so on, but as of right now the output looks like this:
1 -> 2 2 -> 2 3 -> 2 4 -> 2

import java.util.Scanner;

Scanner Case3Scanner = new Scanner(System. in );
System.out.println("Nivel de exactitud? (iteraciones)?");
//e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! + ..
int e_stop = Case3Scanner.nextInt();
System.out.println("--------------");

double e_total = 1; //this is the result we will output
double e_divisor = 1; //this is the number we will get the factorial of of
long e_fact = 1; //this is the factorial of e_divisor
for (int e = 1; e <= e_stop; e++) {
    //this for-loop should repeat r_stop times.
    //this next for-loop should make e_fact equal the factorial of e_divisor     
    for (int ef = 2; ef <= e_divisor; ef++) {
        e_fact *= ef;
    }
    e_total += 1 / e_fact;
    System.out.println(e_total);
    e_divisor += 1;
}
1 Answers

You have 2 mistakes in your code.

One is integer division: e_total += 1/e_fact

This line does integer division, which means you get a truncated integer result (for example, dividing 5/2 in Java would give a result of 2).

To signal that you do not want to do integer division, you need to do something like

e_total += 1D / e_fact (D for double) or e_total += 1.0 / e_fact

You are also calculating the factorials incorrectly.

e_fact already has the result from the previous iteration, so you don't need to multiply it in a loop.

        //e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! + ..
        int e_stop = 4;
        System.out.println("--------------");

        double e_total = 1;    //this is the result we will output
        long e_fact = 1;    //this is the factorial of e_divisor

        for (int e = 1; e <= e_stop; e++) {
            e_fact *= e;
            e_total += 1.0 / e_fact;
            System.out.printf("e: %d, e_fact: %d, e_total: %f\n", e, e_fact, e_total);
        }

Output:

e: 1, e_fact: 1, e_total: 2.000000
e: 2, e_fact: 2, e_total: 2.500000
e: 3, e_fact: 6, e_total: 2.666667
e: 4, e_fact: 24, e_total: 2.708333
Related