In this example, we use the while loop method to calculate 1 + 1/2! + 1/3! +... 1/20!
At the beginning, I thought the factorial could be directly written, like this.
package com.lixiyu;public class Count1 {public static void main(String[] args){ int i=1; int sum=0; while(i<=20){ sum+=(1/i!); i++; } System.out.println("sum="+sum);}}
It is always at the factorial position "!". Error message: java Syntax error on token "! ", Delete this token
I thought about it later! It cannot be used directly. After Google, we found that a mathematical package was called: java. math. BigDecimal.
However, I read the API documentation and did not clarify this usage. Half-Knowledge
First, paste the source code and ponder over it.
Package com. lixiyu; import java. math. bigDecimal; public class Count1 {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 }}
Compile the running result:
1 + 1/2! + 1/3! ... 1/20! The calculation result of is equal to: 1. 7182818284590452236725888 .............
This article is from the "ToBeContinued" blog, please be sure to keep this source http://leexy.blog.51cto.com/4136883/1302890