题目:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?
代码:
/**
* 年龄
* @author cheng
*
*/
public class TwentyThree {
public int age(int n){
if(n==1)
return 10;
if(n>=2){
return age(n-1)+2;
}
else{
return 0;
}
}
public static void main(String[] args){
TwentyThree twentyThree=new TwentyThree();
int age=twentyThree.age(5);
System.out.println("第五个人"+age+"岁");
}
}
输出结果:
第五个人18岁