tonglin0325的个人主页

Java递归算法——阶乘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Factorial_demo {

public static void main(String[] args) throws Exception{
// TODO 自动生成的方法存根
System.out.println("输入数字:");
int theNumber = getInt();
int theAnswer = factorial(theNumber);
System.out.println("阶乘:"+theAnswer);
}

public static int factorial(int n){ //递归
if(n == 1)
return 1;
else
return (n*factorial(n-1));
}

//输出方法
public static String getString() throws IOException{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}

//输出方法
public static int getInt() throws IOException{
String s = getString();
return Integer.parseInt(s);
}
}