Java题,高手帮忙解答啦!!!!

来源:百度知道 编辑:UC知道 时间:2024/07/03 12:44:49
编写程序,输出数学常量 e 的值:e=1+1/1!+1/2!+1/3!+....+1/n!

public class MathE {

public static double step(int n ) {
double d = 1;
for(int i = 1; i <= n; i ++) {
d *= i;
}
return d;
}

public static void main(String[] args) {
int len = 100;
double de = 1.0;
for(int i = 1; i <= len; i ++) {
de += 1.0 / MathE.step(i);
}
System.out.println(de);
System.out.println(Math.E);
}

}

如果要完成作业的话,这样就可以的,不过要想更好一点,还可以加上 try--catch 语句,初学的话就不用加了,呵呵,楼上的兄弟写的比我的要好的,都可以看一下哦!!
class TestMath {
double d = 1;
public double factoral(double x) {
for(double i=1;i<x;i++){
d *= i;
}
return d;
}
}
public class Test_e {
public static void main(String[] args) {
double dou = 0.0;
double j = 5.0;
TestMath tm = new TestMath();
for(int i=1;i<j;i++){
dou += 1/tm.factoral(j);
}
System.out.println(dou);
}