0
Fibonacci - for loop
#include <iostream> using namespace std; int main() { int x1, x2, x3; int n, i; cout<<"Please enter a number"<<endl; cin>>n; x1=0; x2=1; x3=0; for(i=1, i<=n, i++) { x3=x2+x1; x2=x3; x1=x2; } cout<<"fibonacci is "<<x3<<endl; return 0; } Someone can tell me why this program didn't work?
2 Réponses
+ 1
try writing "course<<X3<<endl" inside the loop
+ 1
1st error is that your for loop's syntax are incorrect, instead of using the comma, use ;
for(i=1, i<=n, i++) => for(i=1; i<=n; i++)
also define i inside the for loop instead of outside like
for( int i = 1; i <= n; i++ )
2nd error you have is that you are assigning x3 to x2, and then x2 to x1, which is the same as assigning x1 to x3 so you now end up with x1 and x2 being the same and now you end up with all the powers of 2 ( 1 + 1 = 2, 2 + 2 = 4, 4 + 4 = 8 etc... )
To fix that swap the order,
x1 = x2;
x2 = x3;
The last error you have left now is that your fibonacci sequence ( assuming the other errors are fixed ) starts with 1, 2, 3, 5, 8...
while the real fibonacci starts with 1, 1, 2, 3, 5, 8...
( and sometimes 0, 1, 1, 2, 3, 5, 8... )
and to fix that you should give x3 a starting value of 1.
However now the offset is off by 1 ( entering 4 will return 5, instead of 3 )
and to fix that you should change i <= n to i < n
Next time please post your code in the playground and post a link to there.