0

I'd like to the euler number e for a number n inputed by the user, there's something wrong with the logical part, I can't seem to get the correct answer of 2.5 when inputting 2, instead i get 2. In fact I always get an answer of 2 no matter what the input is. The problem is in the euler method because the factorial prints the correct answer. here is the code.

import java.util.*;

 public class pract5ex3 {
    public static int fact (int n){
    if (n==0 || n==1){
            return 1;
    }
    else {
    return n*fact(n-1);
    }

}
public static double constantRec(int n){
    if (n == 0){

    return 1;
    }
    else {

    return 1/fact(n)+constantRec(n-1);
    }
}

public static void main (String []args) {
    Scanner s= new Scanner (System.in);
    System.out.println("enter number");
    int n =s.nextInt();

    int factorial = pract5ex3.fact(n);
    double euler = pract5ex3.constantRec(n);
    System.out.println(factorial);
    System.out.println(euler);
}

}

2 Answers2

3

Beware of Integer division.

Use:

1.0/fact(n)

To get the double value.

Community
  • 1
  • 1
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
2

The expression 1/fact(n) does integer division which will yield zero if factorial is greater than one. Simply change it to 1.0/fact(n).

Howard
  • 38,639
  • 9
  • 64
  • 83