分别用do-while和for循环计算1+1/2!+1/3!+1/4!+…前20项之和
1.do-while
public class and {
public static void main(String[] args){
double sum =0;
int a=1;
int i=1;
do{
a*=i;
sum +=1.0/a;
i++;
}while(i<=20);
System.out.println(sum);
}
}
2.for
public class and1 {
public static void main(String[] args) {
double sum = 0;
int a = 1;
for (int i = 1; i <= 20; i++) {
a *= i;
sum += 1.0 / a;
}
System.out.println(sum);
}
}