2017-11-11
Program:
求解:1+2!+3!+...+n!的和。
代码如下:
1 /* 2 * 求解:1+2!+3!+...+n!的和 3 * 4 * Date Written:2017-11-11 5 * 6 * */ 7 8 package test; 9 10 import java.util.Scanner; 11 12 public class TestDemo { 13 14 public static void main(String args[]) { 15 16 int n = 0; //接受用户输入,定义求解到最大数的阶乘 17 Scanner scan = new Scanner(System.in); 18 19 System.out.println( "Please input the value of n:" ); 20 n = scan.nextInt(); //取得用户输入 21 22 System.out.println( "The result is " + getResult(n) ); 23 24 scan.close(); //关闭scan; 25 26 } 27 28 //求解阶乘 29 public static int getResult(int n) { 30 31 int sum = 0; //存储最终结果 32 int temp = 1; //当前i的阶乘 33 for( int i = 1; i <= n; i++) { 34 35 temp *= i; 36 sum += temp; 37 } 38 39 return sum; 40 } 41 42 43 }
初学小白,请多指教!