今天看到有萌新问这个怎么实现,看了下百度的答案,很不明确还有写两个do where解决的,一步到位就可以!直接上代码:
public class Demo {
public static void main(String[] args) {
/*
计算n!的和
*/
BigDecimal result = new BigDecimal(1);
for (int i = 1; i <= 100; i++) {
result = result.multiply(BigDecimal.valueOf(i));
}
System.out.println("计算n!:" + result);
/* ----------------------------------------方法一------------------------------------------------ */
/*
计算1!+2!+....+100!的和
方法1:
*/
BigDecimal result1 = BigDecimal.ZERO;
BigDecimal m1 = BigDecimal.ONE;
for (int j = 1; j <= 100; j++) {
m1 = m1.multiply(BigDecimal.valueOf(j));
result1 = result1.add(m1);
}
System.out.println("方法一:1!+2!+...+100! = " + result1.toString());
/* ------------------------------------------方法二------------------------------------------ */
/*
计算1!+2!+....+100!的和
方法2:
*/
BigDecimal result2 = BigDecimal.ZERO;
BigDecimal m2 = BigDecimal.ONE;
int k = 1;
do {
m2 = m2.multiply(BigDecimal.valueOf(k));
result2 = result2.add(m2);
k++;
} while (k <= 100);
System.out.println("方法二:1!+2!+...+100! = " + result2.toString());
}
}