简体   繁体   中英

Approximation of e in java

I am trying to get approximation of constant e where e = 2 + 1/2! + 1/3! + 1/4! + ....... every time I run the code I always! get 2. I would appreciate it if you could correct my code :)

import java.util.Scanner;

public class E
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);

    System.out.println("How many iterations");

    //n = iterations
    int n = scan.nextInt();

    long factor =1;  //starts at 1
    long e = 1;   //e starting point


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

    System.out.println(e);

  }
}

You are performing integer division, which in Java, truncates any decimal result so that the result is always an integer. This is the line:

e +=  1/factor;

That is causing you to add 0 many times, which isn't what you need here.

Use a double literal 1.0 to force floating-point calculation.

e +=  1.0/factor;

Also, mathematically e is not an integer (it's irrational and transcendental), so long is an inappropriate data type to use. Declare e to be double .

After these changes, this is the output I get:

How many iterations
20
2.7182818284590455

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM