多种方式求阶乘

package testBlog;

import java.util.Scanner;
//用非递归的方式求阶乘
public class Test {
    public long getSolution(int n) {// 计算阶乘的方法
        if (n == 0) {// 如果输入的数字是0,则阶乘结果就是1
            return 1;
        }

        long sum = 1;
        for (int i = 1; i <= n; i++) {
            sum = sum * i;
        }
        return sum;

    }

    public static void main(String[] args) {
        System.out.println("请输入要求阶乘的数字:");
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        Test ex = new Test();
        System.out.println(ex.getSolution(a));
    }
}

这是用非递归的方式求阶乘.难点在于sum = sum*i此处.输出时不要忘记用syso,因为默认的返回值不代表会输出.

 1 package testBlog;
 2 
 3 import java.util.Scanner;
 4 
 5 //用递归的方式求阶乘
 6 public class Test {
 7     public static long getSolution(int n) {
 8         if (n == 0) {
 9             return 1;
10         }
11         return n * getSolution(n - 1);// 此处发生递归
12 
13     }
14 
15     public static void main(String[] args) {
16         System.out.println("输入要求阶乘的数字:");
17         Scanner sc = new Scanner(System.in);
18         int a = sc.nextInt();
19         System.out.println(getSolution(a));// 静态方法直接调用
20     }
21 }

强烈注意:使用递归时一定要写上递归的边界,不然会出现StackOverflowError错误.这段代码中,递归的边界就在于if(n==0)处,少了这段代码程序就会报错.

原文地址:https://www.cnblogs.com/ssC2H4/p/8125643.html