JAVA-阶乘的和
题目:编写Java Application程序,分别用do-while和for循环计算1+1/2!+1/3!+1/4!..的前20项和。
- 分析:递归求解
public class factorial {
public static void main(String[] args) {
double temp=1;
double sum=0.0;
//for循环方法
for(int t=1;t<=20;t++){
temp*=(1.0/t);
sum+=temp;
}
System.out.println("使用for循环计算前20项的和是:"+sum);
//do-while方法
int t1=2;
do{
temp*=(1.0/t1);
sum+=temp;
t1++;
}while(t1<=20);
System.out.println("使用do-while循环计算前20项的和是"+sum);
}
}
- 运行结果如下