Practice April 30, 2018

Real column 019 Calculate 1! The value of +1/2!+1/3!+...+1/10!

1  import java.math.BigDecimal;
 2  public  class Factorial 
 3  {
 4      public  static  void main(String[] args)
 5      {
 6          BigDecimal sum = new BigDecimal(0.0);                      // Use BigDecimal class 
7          BigDecimal factorial = new BigDecimal(1.0 );                // Calculation result of factorial term 
8          int i = 1;                                                 // Loop increment 
9          while (i <= 10 )
 10         {
 11              sum= sum.add(factorial);                               // accumulate the result of the factorials 
12              ++i;                                                   // add 
13 to i              factorial = factorial.multiply( new BigDecimal(1.0/i)); // calculate the factorial term 
14          }
 15          System.out.println("1+1/2!+1/3!...1/10! The calculation result is as follows:\n"+sum); // Output calculation result 
16      }
 17  
18 }

 

Remarks: 1. Refer to the BigDecimal class to accurately find the value of the factorial

           2. Use multiply() to perform factorial operation, and the calculation logic is as follows: For example, calculate 1! The value of +1/2!+1/3!+...+1/10! 

1

1

1*1/2

1+1*1/2

1*1/2*1/3

1+1*1/2+ 1*1/2*1/3

1*1/2*1/3*1/4

1+1*1/2+ 1*1/2*1/3+1*1/2*1/3*1/4   

.

.

.

      

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325120278&siteId=291194637