Home > Back-end >  About writing the Fibonacci sequence (f (n)=f (n - 1) f (n - 2))
About writing the Fibonacci sequence (f (n)=f (n - 1) f (n - 2))

Time:09-16


The code below
 # include 
Long long int the Fibonacci (int a) {
int i;
Long long int=1 f1, f2=1, the f3.
If (a
=2)return 1;
The else {
For (I=3; I<=a; I++) {
F3=f1 + f2;
F1=f2; F2=f3;
}
Return the f3.
}
}
Int main () {
Int I, n, a;
The scanf (" % d ", & amp; N);
for(i=0; IThe scanf (" % d ", & amp; A);
Printf (" % LLD \ n ", Fibonacci (a));
}
return 0;
}

Wrong answer, where is big problem in the

CodePudding user response:

Should still overflows, you change of type double try
#include
Double Fibonacci (int a)
{
int i;
=1 double f1, f2=1, the f3.
If (a & lt;=2) return 1;
The else
{
For (I=3; i <=a; I + +)
{
F3=f1 + f2;
F1=f2;
F2=f3;
}
Return the f3.
}
}
Int main ()
{
Int I, n, a;
The scanf (" % d ", & amp; N);
For (I=0; i {
The scanf (" % d ", & amp; A);
Printf (" % 0 f \ n ", Fibonacci (a));
}
return 0;
}

CodePudding user response:

 # include 
{int the Fibonacci (int a)
If (a
=2)return 1;
The else {
Return the Fibonacci (a - 1) + Fibonacci (a - 2);
}
}
Int main () {
Int I, n, a;
The scanf (" % d ", & amp; N);
for(i=1; IPrintf (" % d \ n ", Fibonacci (I));
}
return 0;
}
  • Related