编写一个递归函数,求解Fibonacci数的问题的某项的值,编写测试程序从键盘输入指负项,并输出Fibonacci数列指定项的值
编写一个递归函数,求解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。如果需要,可以修改函数的定义来更改这个假定。
报告相同问题?