12 阶乘

package com.wys.java;

public class facDemo {
    //方法不能嵌套定义
    //求阶乘的方法
    public  int fac(int n){
        int result=1;
        for(int i=1; i<=n; i++){
            result *= i;
        }
        return result;
    }

    public static void main(String[] args) {
        facDemo facdemo = new facDemo();
        int fac3 = facdemo.fac(3);
        System.out.println("3! = "+fac3);

        //求1!+2!+3!+4!+5!
        int sum=0,facx=0;
        for(int i=1; i<=5; i++){
            facx = facdemo.fac(i);
            sum += facx;
        }
        System.out.println("1!+2!+3!+4!+5! = "+sum);
    }
}

结果:

猜你喜欢

转载自www.cnblogs.com/CPU-Easy/p/12127611.html