`

递归算法:阶乘

    博客分类:
  • java
 
阅读更多
import javax.swing.JOptionPane;

//递归算法:求n的阶乘:n! 
public class Factorial {

	public static void main(String[] args) {
		int n = 0;
		try {
			//输入参数
			n = Integer.parseInt(JOptionPane.showInputDialog("请输入n: "));
		} catch (NumberFormatException e) {
			System.out.println("数据格式不对!,请输入正整数。");
			return;
		}
		System.out.println(method(n));
	}

	//递归方法
	public static int method(int n) {
		if (n < 1) {
			//-1 代表错误结果
			return -1;
		} else if (n == 1) {
			return 1;
		} else {
			//再次调用method(int n)
			return n * method(n - 1);
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics