递归方法是指在方法体内调用自身的方法。对于求阶乘的问题,可以使用递归方法。

public class Factorial {
    public static void main(String[] args) {
        int n = 5;
        int result = factorial(n);
        System.out.println(n + "! = " + result);
    }
    
    public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
}

输出结果为:

5! = 120

在递归方法中,当 n 等于 0 或者 1 时,直接返回 1。否则,将 n 与 n-1 的阶乘相乘,再返回结果。这样就可以逐步地将问题分解成更小的子问题,直到最终得到结果。

java35、利用递归方法求5!。

原文地址: https://www.cveoy.top/t/topic/i4B1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录