While loop inside for loop fibonacci
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
So I want function to plot the fibonacci series and i want it to stop when it recheas m.
I'm not sure what the error is, it just doesn't run.
Thanks for helping!
function f = fibbo3(m)
n=100;
f=zeros(1,n);
f(1)=1;
f(2)=1;
for k=3:n
while f(k) <= m
f(k) = f(k-1) + f(k-2);
end
end
end
0 comentarios
Respuestas (1)
Image Analyst
el 5 de Abr. de 2021
Don't have the while loop. After you assign f(k), just break if the value is more than m
for k=3:n
f(k) = f(k-1) + f(k-2);
if f(k) >= m
break;
end
end
2 comentarios
Image Analyst
el 5 de Abr. de 2021
When you call it, print out the last one:
f = fibbo3(m);
fprintf('The final Fibonacci number with m=%d is %d.\n', m, f(end));
Or else don't pass back the entire array, just pass back the last element:
function f = fibbo3(m)
% code.... then....
f = f(end); % Extract only the very last element of the vector to pass back.
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!