递归算法,也就是调用方法自身。阶乘算法,N的阶乘为N*(N-1)*…*2*1,1的阶乘是1。
下面是示例的代码:
package com.cqit.edu.test;
import java.util.Scanner;
/**
* @author 肖德俊
* @version Dec 9, 2008 6:02:55 PM
*/
public class Useself {
/**
* @param args
*/
public static long maths(int n) {
long num = 0;
if (n == 1) {
num = 1;
} else {
num = n * maths(n – 1);
}
return num;
}
public static void main(String[] args) {
System.out.println(“=============递归算法演示=================”);
System.out.println(“请输入n值:”);
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(n + “调用递归算法计算阶乘的结果是:” + Useself.maths(n));
}
}