I denne artikel lærer du at udskrive Fibonacci-serier i C ++ programmering (op til n. Periode og op til et bestemt antal).
For at forstå dette eksempel skal du have kendskab til følgende C ++ programmeringsemner:
- C ++ til Loop
- C ++ mens og gør … mens Loop
Fibonacci-sekvensen er en serie, hvor den næste periode er summen af gennemtrængelige to termer. De første to termer i Fibonacci-sekvensen er 0 efterfulgt af 1.
Fibonacci-sekvensen: 0, 1, 1, 2, 3, 5, 8, 13, 21
Eksempel 1: Fibonacci-serien op til n antal udtryk
#include using namespace std; int main() ( int n, t1 = 0, t2 = 1, nextTerm = 0; cout <> n; cout << "Fibonacci Series: "; for (int i = 1; i <= n; ++i) ( // Prints the first two terms. if(i == 1) ( cout << t1 << ", "; continue; ) if(i == 2) ( cout << t2 << ", "; continue; ) nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; cout << nextTerm << ", "; ) return 0; )
Produktion
Indtast antallet af udtryk: 10 Fibonacci-serier: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Eksempel 2: Program til at generere Fibonacci-sekvens op til et bestemt antal
#include using namespace std; int main() ( int t1 = 0, t2 = 1, nextTerm = 0, n; cout <> n; // displays the first two terms which is always 0 and 1 cout << "Fibonacci Series: " << t1 << ", " << t2 << ", "; nextTerm = t1 + t2; while(nextTerm <= n) ( cout << nextTerm << ", "; t1 = t2; t2 = nextTerm; nextTerm = t1 + t2; ) return 0; )
Produktion
Indtast et positivt heltal: 100 Fibonacci-serier: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,