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);
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM