目录
程序清单18_1ComputeFactorial.java
package chapter_18;
import java.util.Scanner;
public class 程序清单18_1ComputeFactorial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a nonnegative integer:");
int n = input.nextInt();
System.out.println("Factorial of " + n + " is " + factorial(n));
}
public static long factorial(int n) {
if(n == 0)
return 1;
else
return n * factorial(n - 1);
}
}
输出结果
Enter a nonnegative integer:4
Factorial of 4 is 24
程序清单18_2ComputeFibonacci.java
package chapter_18;
import java.util.Scanner;
public class 程序清单18_2ComputeFibonacci {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an index for a Fibonacci number:");
int index = input.nextInt();
System.out.println("The Fibonacci number at index "+ index+" is " + fib(index));
}
public static long fib(long index) {
if (index == 0)
return 0;
else if(index == 1)
return 1;
else
return fib(index - 1) + fib(index - 2);
}
}
输出结果
Enter an index for a Fibonacci number:7
The Fibonacci number at index 7 is 13