Friday 19 August 2016

Chapter 5 Exercise 26, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

**5.26 (Compute e) You can approximate e using the following series:
e=1+11!+12!+13!+14!+...+1i!e=1+11!+12!+13!+14!+...+1i!

Write a program that displays the e value for i = 10000, 20000, …, and 100000. (Hint: Because i! = i * (i - 1) * ... * 2 * 1, then i/i! is 1/i*(i-1)
Initialize e and item to be 1 and keep adding a new item to e. The new item is the previous item divided by i for i = 2, 3, 4, . . . .)

public class ProgrammingEx5_26 {
 public static void main(String[] args) {
  double e = 1,p=1;
 
  for (int i = 1; i <= 100000; i++) {
   p=p/i;
   e += p;
   if (i == 10000) {
    System.out.println("e at i = 10000 is " + e);
   } else if (i == 20000) {
    System.out.println("e at i = 20000 is " + e);
   } else if (i == 100000) {
    System.out.println("e at i = 100000 is " + e);
   }
  }
   
  System.out.println("Java's e is " + Math.E);
 
 }
}

No comments :

Post a Comment