matlab作业:斐波那契数列
clc;
clear;
n=input('请输入你想知道的第几个斐波那契数:');
%%matlab自带的斐波那契数列函数
answer1=fibonacci(n);
Answer1=sprintf("方法一第%d项的斐波那契数:%d",n,answer1);
disp(Answer1);
%%迭代计算斐波那契数列函数
answer2=Fibonacci1(n);
Answer2=sprintf("方法二第%d项的斐波那契数:%d",n,answer2);
disp(Answer2);
%%递归计算斐波那契数列函数
answer3=Fibonacci2(n);
Answer3=sprintf("方法三第%d项的斐波那契数:%d",n,answer3);
disp(Answer3);
function answer2 = Fibonacci1(n)
if (n<0)||(round(n)~=n)
warning('请输入非负数');
answer2=[];
return;
elseif n<2
answer2=n;
else
answer2=Fibonacci1(n-1)+Fibonacci1(n-2);
end
end
function answer3 = Fibonacci2(n)
if (n<0)||(round(n)~=n)
warning('请输入非负数');
answer3=[];
return;
elseif n<=2
answer3=n;
else
a=1;
b=1;
answer3=1;
for time =3:n
answer3=a+b;
a=b;
b=answer3;
end
end
end