Two common approaches for generating the Fibonacci series:
I met another solution
#include <iostream> using namespace std; void fibo() { static int y = 0; static int x = 1; cout << y << endl; y = x + y; x = y - x; } int main() { for (int i = 1; i <= 1; i++) { fibo(); } return 0; }
This solution works fine in initial launches, but compared to the traditional and recursive approach, does it have any significant flaws?
I am sure that static variables would add to the complexity of space, but at least we are not building a stack of function tables using recursion, right?
The disadvantages that I can immediately see:
, , - , . ( , ++, # Java IEnumerable<T> Iterable<T>.)
IEnumerable<T>
Iterable<T>
, , , (, , - , ), , , . , , , . :
class FiboNumbers { public: FiboNumbers() : x_(1), y_() {} int getNext() { x_ += y_; y_ = x_ - y_; return x_; } private: int x_, y_; };
, , , .
: , , , , , , 0 1 1 2...
++ ( 1,5 ).
, .
#include<iostream> using namespace std; void fibseries(long int n) { double x=0;double y=1; for (long int i=1;i<=n;i++) { if(i%2==1) { cout<<x<<" "; x=x+y; } else { cout<<y<<" "; y=x+y; } } } main() { long int n=0; cout<<"The number of terms "; cin>>n; fibseries(n); return 0; }
, . , , , , . ( , , , "0" .) :
"0"
int y = 0; int x = 1; for ( int i = 0; i < count; ++ i ) { std::cout << y <<std::endl; y = x + y; x = y - x; }
? , .
, , n- , n-1- .
, , , , , , .
class, Sevis, , : , ( ), , , ..
class
I think this pointer approach will be more useful for you.
void main() { int i,p, *no,factorial,summ; int fib(int p); clrscr(); printf("\n Enter The Number:"); scanf("%d", no); printf("\n The Fibonnacci series: \n"); for(i=0; i < *no; i++) printf("%d\n", fib(i)); getch(); } int fib(int p) { if(p == 0) return(0); if(p >= 1 && p <= 2) return(1); else return(fib(p - 1) + fib(p - 2)); }