Write a program and use the while statement to calculate 1 + 1/2! + 1/3 !...... + 1/20 !, And output the computing results in the control of Taishan. Requirement 1 + 1/2! + 1/3 !...... + 1/20 !, In fact, it is to calculate 1 + 1*1/2 + 1*1/2*1/3 + ...... + 1*1/2*1/3 *...... * 1/20.
Import java. math. bigDecimal; public class Jiecheng {public static void main (String args []) {BigDecimal sum = new BigDecimal (0.0); // and BigDecimal factorial = new BigDecimal (1.0 ); // The calculation result of the factorial is int I = 1; // the incremental while (I <= 20) {sum = sum. add (factorial); // accumulate the factorial and ++ I; // I add 1 factorial = factorial. multiply (new BigDecimal (1.0/I); // calculate a factorial} System. out. println ("1 + 1/2! + 1/3! ... 1/20! The calculation result of is equal to \ n "+ sum); // output the calculation result }}
Effect: