Write a for loop that calculates the first 35 numbers of the Fibonacci Sequence.
31 次查看(过去 30 天)
显示 更早的评论
Given : The Fibonacci Sequence is a famous sequence, where the value of each number in the list is the sum of the two before it. The first 5 numbers in the Fibonacci Sequence are 0, 1, 1, 2, and 3. As such, any value in element n of the sequence, is the sum of element n-1 and element n-2.
Find : Create a row vector named fib that contains the sequence of numbers.
Hint: You might want to start your loop at the 3rd element in fib. For the Fibonacci to work, you must know the first 2 digits in the sequence ahead of time.
Issue: I am new to loops, I know there is a way to logically do this. But unfortunately I can't get it to work in the way I have below.
My solution:
% Remember you are filling variable fib
fib=sum(n1+n2)
for n=1:35
if n1<n
n2=n1+1
end
end
2 个评论
Steven Lord
2024-3-19
Can you describe how you'd compute the Fibonacci numbers with pencil and paper? If so, write those steps down in your script file as comments. Then after each of those comments, write down either the code that performs those steps or (if you're not sure how to implement the step) additional comments breaking the step down into smaller pieces that you can implement.
Here's a hint of the first two steps.
% Step 1: Assign the first value in the sequence to the first element of fib
% Step 2: Assign the second value in the sequence to the second element of fib
What's
% Step 3:
采纳的回答
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!