C++ output Fibonacci sequence of two implementation methods

  • 2020-04-02 01:57:04
  • OfStack

Definition:

The Fibonacci sequence refers to a sequence of 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
This sequence starts with the third term, and each term is equal to the sum of the first two terms.

Take the first 20 items in the output Fibonacci sequence as an example:

Method one:
The standard practice of comparison is achieved with the help of the third variable.


#include<iostream>  
using namespace std;
int main(){
    int f1=0,f2=1,t,n=1;
    cout<<" The sequence of the first 1 A: "<<f1<<endl;
    cout<<" The sequence of the first 2 A: "<<f2<<endl; 
    for(n=3;n<=20;n++){
        t=f2;
        f2=f1+f2;
        f1=t;
    cout<<" The sequence of the first "<<n<<" A: "<<f2<<endl; 
    }     
    cout<<endl;
    return 0;
}

Method 2:
This is the site when you think of the method, you can pass two points, a loop output two items.

#include<iostream>  
using namespace std;
int main(){
    int f1=0,f2=1,t,n=1;
    cout<<" The first term of the sequence: "<<f1<<endl;
    cout<<" The second term of the sequence: "<<f2<<endl; 
    for(n=2;n<10;n++){
     f1=f1+f2;
 cout<<" The sequence of the first "<<(2*n-1)<<" Item: "<<f1<<endl;
 f2=f1+f2;
 cout<<" The sequence of the first "<<(2*n)<<" Item: "<<f2<<endl; 
    }  
 cout<<endl;
 return 0;
}


Related articles: