n!=1×2×3×...×n
阶乘也可以用递归方式定义:
0!=1,n!=(n-1)!×n
/** * 1、使用循环实现阶乘 */ public class Factorial { public static int fact(int sum) { int n = 1; // 查验输入错误 if (num < 0) { System.out.println("输入错误,必须为正整数"); return -1; } else { // 循环num次 for (int i = 1; i <= num; i++) { // 每次循环一次就进行一次乘法运算 n = n * i; } // 返回阶乘结果n return n; } } public static void main (String[] args) { int count = fact(3); System.out.println(count); } }
public class Factorial { public static int fact(int n) { // 验错 if (n < 0) { System.out.print("输入错误,必须为正整数"); return -1; } else if (n == 1) { return 1; } // n的阶乘就等于n乘(n-1)的阶乘 return fact(n - 1) * n; } public static void main(String[] args) { System.out.println(fact(3)); } }
原文:https://www.cnblogs.com/TSCCG/p/14710209.html