# 如何用程式近似e？

Euler’s number, e, is used as the base of natural logarithms. It can be approximated using the following formula：e = 1+1/1!+1/2!+1/3!+1/4!+1/5!+…+1/(n-1)!+1/n!

Write a program that approximates e using a loop that terminates when the difference between two successive values of e differ by less than 0.0000001.

Rating

題目的意思是要你用廻圈來計算 e 值。例如：

1st calculation: 1 + 1/1!

2nd calculation: 1st + 1/2!

3rd calculation: 2nd + 1/3!

...

(n)th calculation: (n-1)th calculation + 1/n!

如何決定 n 值則是檢定最後面的這個 1/n! 是否小於目標值 0.0000001。請參考我的做法

public class Euler {

public static void main(String[] args) {

double appro = 1.0D;

int count = 1;

while (true) {

double sum = 1.0D;

for (int i = 1; i < count; i++) {

sum *= i;

}

sum = 1.0D / sum;

if (sum < 0.0000001) {

System.out.println("Last calculation");

System.out.println("n = " + count);

System.out.println("diff = " + sum);

System.out.println("e = " + appro);

System.exit(0);

} else {

appro += sum;

count++;

}

}

}

}

• Login to reply the answers