斐波那契函数不接受0并且不显示最后一项 [英] Fibonacci function not accepting 0 and not displaying the last term only
问题描述
我写了一个函数,显示直到第n个项的斐波那契数列.该代码运行良好,但是我想进行两项更改,但不确定如何执行.
I wrote a function that displays the Fibonacci sequence up to the nth term. The code runs fine, but I want to make two changes and am not sure how to do so.
这是我的代码:
function [ F ] = get_fib( k )
F(1) = 1;
F(2) = 1;
i = 3;
while k >= i;
F(i) = F(i-1) + F(i-2);
i = i + 1;
end
end
第一个问题是代码不接受0
作为输入.我尝试将功能更改为:
The first problem is that the code does not accept 0
as an input. I tried changing the function to:
function [ F ] = get_fib( k )
F(0) = 0;
F(1) = 1;
F(2) = 1;
i = 3;
while k >= i;
F(i) = F(i-1) + F(i-2);
i = i + 1;
end
end
但是出现以下错误:
试图访问F(0);索引必须为正整数或逻辑.
Attempted to access F(0); index must be a positive integer or logical.
get_fib错误(第2行)
F(0)= 0;
Error in get_fib (line 2)
F(0) = 0;
我还希望代码显示序列中的最后一项,而不是整个序列.
I would also like the code to display the last term in the sequence, rather than the entire sequence.
我将功能更改为:
function [ F ] = get_fib( k );
F(1) = 1;
F(2) = 1;
i = 3;
while k >= i;
F(i) = F(i-1) + F(i-2);
i = i + 1;
end
term = F(k)
end
,但仍将其分配给ans
的顺序.
but the sequence it still being assigned to ans
.
如何使我的函数接受0
作为参数并仅显示序列的最后一项?
How can I make my function accept 0
as an argument and only display the last term of the sequence?
推荐答案
由于其他人已经指出了如何修复代码,因此我想向您展示一种计算 nth 斐波那契数的方法无需依赖 F(n-1)和 F(n-2)项计算.
Since others already pointed out how to fix your code, I'd like to show you one approach to calculate the nth Fibonacci number without relying on the F(n-1) and F(n-2) terms calculation.
它涉及黄金比例,您可以在
It involves the golden ratio, and you can read more about its relationship to the Fibonacci sequence here.
function [ F ] = get_fib( n )
% Changed your input variable from k to n (standard notation)
Phi = (1+sqrt(5))/2; % Golden ratio value
F = round((Phi^n - ((-1)^n)/(Phi^n))/sqrt(5)); %nth fibonacci number
end
由于您只对序列的最后一个值感兴趣,因此可以大大加快 n 值的计算速度.
Since you are only interested in the last value of the sequence, it could speed up the calculation for large values of n.
请注意,我已对输出(F
)进行了四舍五入,以避免浮点算术错误.
Note i have rounded the output (F
) to avoid floating point arithmetic errors.
这篇关于斐波那契函数不接受0并且不显示最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!