题目:有 5 个人坐在一起,问第五个人多少岁?他说比第 4 个人大 2 岁。问第 4 个人岁数,他说比第 3 个人大 2 岁。问第三个人,又说比第 2 人大两岁。问第 2 个人,说比第一个人大两岁。最后问第一个人,他说是 10 岁。请问第五个人多大?
程序分析:利用递归的方法,递归分为回推和递推两个阶段。要想知道第五个人岁数,需知道第四人的岁数,依次类推,推到第一人(10 岁),再往回推。
import java.util.Scanner;
public class WangDao {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Input the number of the person: ");
int n = scan.nextInt();
System.out.print("Input the age of the this person: ");
int age = scan.nextInt();
System.out.println("The age of the fifth person is " + func(n, age));
}
public static int func(int n, int age) {
if (n == 5) {
return age;
} else {
return func(n+1, age+2);
}
}
}