Mik*_*key -2 algorithm fibonacci
我正在研究这个问题并试图弄清楚Fibonacci是如何实现的?
public int fibonacci(int x) {
if (x==1) {
return 1;
} else if (x==2) {
return 1;
} else {
return fibonacci(x-1) + fibonacci(x-2)
}
}
Run Code Online (Sandbox Code Playgroud)
我将此序列显示为正确的序列.
1, 1, 2, 3, 5, 8, 13, 21
Run Code Online (Sandbox Code Playgroud)
问题出在5我得到的迭代上7
(5-1) + (5-2) = 4 + 3
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么吗?
它是fibonacci(5 - 1) + fibonacci(5 - 2)序列(5和3)中的前两个数字,而不是(5 - 1) + (5 - 2).
此外,您的代码中存在错误,if (x=2)应该使用==.但是我假设您在写入Stack Overflow时介绍过,或者我认为您不会得到您正在获得的序列.