问题描述
我正在尝试创建一个递归函数调用方法,该方法将打印斐波那契直到特定位置:
I am trying to create a recursive function call method that would print the Fibonacci until a specific location:
1 function f = fibonacci(n)
2 fprintf('The value is %d\n', n)
3 if (n==1)
4 f(1) = 1;
5 return;
6 elseif (n == 2)
7 f(2) = 2;
8 else
9 f(n) = fibonacci(n-1) + fibonacci(n-2);
10 end
11 end
根据我的理解,将递归调用fibonacci函数,直到传递给它的参数n的值为1.然后函数栈将相应地回滚.因此,当我从命令中调用此函数时:
As per my understanding the fibonacci function would be called recursively until value of argument n passed to it is 1. Then the function stack would rollback accordingly. So when I call this function from command:
>> fibonacci(4)
n的值为4,因此第9行的执行方式如下:
The value of n is 4, so line 9 would execute like:
9 f(4) = fibonacci(3) + fibonacci(2);
现在,我相信第一个fibonacci(3)将被调用-因此,再次调用fibonacci(3)
Now I believe that that first fibonacci(3) would be called - hence again for fibonacci(3)
9 if(3) = fibonacci(2) + fibonacci(1);
第3行和第6行的ifs很重要.
The ifs in line number 3 and 6 would take care.
但是现在fibonacci(2)+ fibonacci(1)语句将变为:
But now how fibonacci(2) + fibonacci(1) statement would change to:
if(3) = 2 + 1;
我收到以下错误,无法进一步调试以解决该问题:
I am receiving the below error and unable to debug further to resolve it:
>> fibonacci(4)
The value is 4
The value is 3
The value is 2
The value is 1
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in fibonacci (line 9)
f(n) = fibonacci(n-1) + fibonacci(n-2);
Error in fibonacci (line 9)
f(n) = fibonacci(n-1) + fibonacci(n-2);
请提供一些解决方案的见解,并首先在第9行递归调用哪个参数斐波那契函数.
Please provide some insight for the solution and with which parameter would fibonacci function be recursively called at line number 9 first and consequently.
例如n = 4
f(n) = fibonacci(3) + fibonacci(2);
那么MATLAB将首先调用fibonacci(3)还是fibonacci(2)?
So will MATLAB call fibonacci(3) or fibonacci(2) first?
代码不应该像下面这样:
Shouldn't the code be some thing like below:
1 function f = fibonacci(n)
2 fprintf('The valus is %d\n', n)
3 if (n==1)
4 f(1) = 1;
5 return f(1);
6 elseif (n == 2)
7 f(2) = 2;
8 return f(2);
9 else
10 f(n) = fibonacci(n-1) + fibonacci(n-2);
11 end
12 end
为什么函数中的返回表达式会导致错误?
Why return expression in a function is resulting in an error?
推荐答案
尝试一下:
function f = fibonacci(n)
if (n==1)
f= 1;
elseif (n == 2)
f = 2;
else
f = fibonacci(n-1) + fibonacci(n-2);
end
请注意,这也是一个递归(仅对每个n计算一次):
Note that this is also a recursion (that only evaluates each n once):
function f=fibonacci(n)
f=additive(n,1,2);
function a=additive(n,x0,x1)
if(n==1)
a=x0;
else
if(n==2)
a=x1;
else
a=additive(n-1,x1,x0+x1);
end
end
这篇关于递归函数以生成/打印斐波那契数列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!