I den här artikeln lär du dig att skriva ut Fibonacci-serier i C ++ programmering (upp till nionde terminen och upp till ett visst antal).
För att förstå detta exempel bör du ha kunskap om följande C ++ programmeringsämnen:
- C ++ för Loop
- C ++ medan och gör … medan Loop
Fibonacci-sekvensen är en serie där nästa term är summan av genomträngliga två termer. De två första termerna i Fibonacci-sekvensen är 0 följt av 1.
Fibonacci-sekvensen: 0, 1, 1, 2, 3, 5, 8, 13, 21
Exempel 1: Fibonacci-serien upp till n antal termer
#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
Ange antalet termer: 10 Fibonacci-serier: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Exempel 2: Program för att generera Fibonacci-sekvens upp till ett visst 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
Ange ett positivt heltal: 100 Fibonacci-serier: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,