Coding fibonacci without using fibonacci matlab code
21 ビュー (過去 30 日間)
古いコメントを表示
I've written this code so far. Here is the question being asked:
Write a MATLAB program that creates and outputs the first 30 numbers in the Fibonacci series. The Fibonacci series is 0, 1, 1, 2, 3, 5, 8, 13, 21, … The first two numbers are 0 and 1. Each subsequent number is the sum of the two preceding numbers. So, the next number in the example above is 13 + 21 = 34. And the next number is 21 + 34 = 55. And so on. In your code, explicitly assign the first two numbers in the series, then built up the rest of series using a for-loop. Do not use MATLAB's fibonacci function (available in the Symbolic Math Toolbox). We're looking for very specific output in this question. Output the 30 numbers, 5 numbers per line over 6 lines. Use an 8-character field width for each number. One final thing. Create all the output using a single fprintf statement that executes just once
And here is the code I've written so far. I need help getting the format of the code, and just clarifying that I did the right thing?
clear, clc
x = 'Input first term of the Fibonacci sequence: ';
input_first_term = input(x);
y = 'Input second term of the Fibonacci sequence: ';
input_second_term = input(y);
s(1)=input_first_term;
s(2)=input_second_term;
for i=3:10
s(i)=s(i-2)+s(i-1);
end
disp(s)
d=(1:10);
polarplot(d,s)
2 件のコメント
Walter Roberson
2020 年 3 月 19 日
Not obvious what polarplot has to do with Fibonacci ?
x = 'Input first term of the Fibonacci sequence: ';
No, the question says specifically " The first two numbers are 0 and 1.". Do not ask the user what values to use, just do an assignment statement.
for i=3:10
The assignment requires 30 values.
Create all the output using a single fprintf statement that executes just once
You did not do any fprintf() at all.
回答 (1 件)
James Tursa
2020 年 3 月 19 日
編集済み: James Tursa
2020 年 3 月 20 日
Hint: The fprintf( ) function will automatically wrap around if you have too many variables than the format string allows for. E.g., If I try to print four numbers using a string that only prints two numbers (each to a 5 digit field) with a newline at the end I will get this result:
>> fprintf('%5d%5d\n',1:4)
1 2
3 4
Modify that to get the result in the format you want for your specific case.
3 件のコメント
Walter Roberson
2020 年 3 月 20 日
The loop you had originally
for i=3:10
s(i)=s(i-2)+s(i-1);
end
was fine other than stopping at 10 instead of going to 30.
You would not fprintf() until after you had computed all of s
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!