码迷,mamicode.com
首页 > 其他好文 > 详细

计算阶乘的和

时间:2016-11-21 07:59:38      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:int   --   bsp   while   blog   class   str   factor   stat   

 

编写java程序,使用while循环语句计算1+1/2!+1/3!+...+1/20!之和

 1 public class Factorial {
 2 
 3     public static void main(String[] args) {
 4         int n = 20;
 5         double sumFactorial = 0.0;
 6         while (n > 0) {
 7             sumFactorial += (1.0 / calculateFactorial(n));
 8             n--;
 9         }
10         System.out.println("1+1/2!+1/3!+...+1/20!=" + sumFactorial);
11 
12     }
13 
14     public static long calculateFactorial(int num) {// 计算数的阶乘,由于20的阶乘超过了int所表示数的范围,所以这里用long
15         long sum = 1L;
16         while (num > 0) {
17             sum *= num;
18             num--;
19         }
20         return sum;
21     }
22 
23 }

技术分享

 

计算阶乘的和

标签:int   --   bsp   while   blog   class   str   factor   stat   

原文地址:http://www.cnblogs.com/feimanzhh/p/6084006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!