Coding fibonacci without using fibonacci matlab code

30 visualizzazioni (ultimi 30 giorni)
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 Commenti
Walter Roberson
Walter Roberson il 19 Mar 2020
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.

Accedi per commentare.

Risposte (1)

James Tursa
James Tursa il 19 Mar 2020
Modificato: James Tursa il 20 Mar 2020
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 Commenti
Charlotte Reed
Charlotte Reed il 20 Mar 2020
fprintf('%5d%5d\n',1:30)
for i=30
s(i)=s(i-2)+s(i-1);
s(1)=0
s(2)=1
end
the idea i have so far?
Walter Roberson
Walter Roberson il 20 Mar 2020
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

Accedi per commentare.

Categorie

Scopri di più su MATLAB in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by