Java实例——计算 1+2!+3!+...+20!的和

计算 1+2!+3!+...+20!的和

1、使用嵌套循环实现

public class FactorialAdd {
    public static void main(String[] args) {
        //计算 1+2!+3!+...+20!的和
        System.out.println(" 1+2!+3!+...+20!的和为:"+factAdd());

    }
    //使用嵌套循环计算 1+2!+3!+...+20!的和、
    public static double factAdd(){
        double sum = 0;
        for(int i = 1 ; i <= 20 ; i++){
            int result = 1;
            for(int j = 1 ; j <= i; j++){
                result *= j;
            }
            sum += result;
        }
        return sum;
    }
}

 

2、使用递归实现

public class FactorialAdd {
    public static void main(String[] args) {
        //计算 1+2!+3!+...+20!的和
        System.out.println(" 1+2!+3!+...+20!的和为:"+factAdd());

    }
    //和计算
    public static double factAdd(){
       double result = 0;
        for(int i = 1 ; i <= 20 ; i++){
            result += fact(i);
        }
        return result;
    }
    //阶乘计算
    public static int fact(int n){
       if(n == 1){
           return 1;
        }else{
            return n*fact(n-1);
        }
    }
}

 

posted @ 2021-04-12 09:03  泰初  阅读(2973)  评论(0编辑  收藏  举报