java用do-while循环计算1 1/2! 1/3! 1/4! ...的前20项和

如题所述

先写个求阶乘的方法:
public static int jieCheng(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

然后如你要求的用dowhile()循环计算:(也给你写了个方法)
public static double caculate(int n) {
double sum = 0.0;
int i=1;
do{
sum = sum + 1.0 / jieCheng(i);
i++;
} while(i<=n)

return sum;
}

用的时候直接调用这个方法就可以了,例如计算前20的:caculate(20);
n随便你多少 o(∩_∩)o...哈哈
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-03-17
public class MyTest {
public double getResult(){
double result = 0;
int i = 1;
do{
result += 1.0/getDenominator(i);
i++;
}while(i <= 20);
return result;
}

private int getDenominator(int i){
for(int j = i-1; j >= 1 ; j--){
i *= j;
}
return i;
}

public static void main(String[] args) {
MyTest test = new MyTest();
System.out.println(test.getResult());
}
}
第2个回答  2008-03-18
楼上的两个都很好

1楼的我试过,可以不过result =0.0;更好点.

2楼的更好,更全面.

都是高手啊.....