python3练习100题——028

原题链接:http://www.runoob.com/python/python-exercise-example28.html

题目有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?

我的代码:

def fun(x):
    if x==1:
        return 10
    else:
        return fun(x-1)+2

if __name__ =='__main__':
    print(fun(5))

所以用递归就好,很容易。

猜你喜欢

转载自www.cnblogs.com/drifter/p/9190308.html