编程: 第1个人10,第2个比第1个人大2岁,依次递推,请用递归方式计算出第8个人多大?
这里使用递归实现,如果使用循环的话太好做了,但是如果使用递归的话就有点绕圈圈,以下是实现方案之一:
package com.test;
public class ComputeAge {
/**
* 递归函数的执行过程具有三个特点:
* 1、函数名相同 2、不断地自调用 3、最后被调用的函数要最先被返回
* @param n
* @return
*/
public static int getComputeAge(int n) {
int age = 0;
if (n == 1) {
age = 10;
} else {
age = getComputeAge(n - 1) + 2;
}
return age;
}
public static void main(String[] args) {
System.out.println(getComputeAge(8));
}
}