编写一个递归函数,求解Fibonacci数的问题的某项的值,编写测试程序从键盘输入指负项,并输出Fibonacci数列指定项的值
这是一个简单的递归函数,用来求解斐波那契数列的某一项的值:
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
下面是一个使用该函数的测试程序,它从键盘输入指定项,并输出斐波那契数列指定项的值:
# Get the n-th item in the Fibonacci sequence
n = int(input("Enter the item number in the Fibonacci sequence: "))
# Compute the value of the n-th item in the sequence
value = fibonacci(n)
# Print the result
print(f"The value of the {n}-th item in the Fibonacci sequence is {value}.")
请注意,上面的代码假定斐波那契数列的第一项为0,第二项为1。如果需要,可以修改函数的定义来更改这个假定。
def fibo(n):
"""递归函数实现斐波那契数列"""
if n == 1 or n == 2:
return 1
else:
return fibo(n-1) + fibo(n -2)
if __name__ == '__main__':
n = int(input("请输入数列的项数:"))
res = fibo(n)
print(res)
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!