C ++程序使用递归查找斐波那契数

以下是使用递归的斐波那契数列的示例。

示例

#include <iostream>
using namespace std;
int fib(int x) {
   if((x==1)||(x==0)) {
      return(x);
   }else {
      return(fib(x-1)+fib(x-2));
   }
}
int main() {
   int x , i=0;
   cout << "Enter the number of terms of series : ";
   cin >> x;
   cout << "\nFibonnaci Series : ";
   while(i < x) {
      cout << " " << fib(i);
      i++;
   }
   return 0;
}

输出结果

Enter the number of terms of series : 15
Fibonnaci Series : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

在上面的程序中,实际的代码存在于函数“ fib”中,如下所示:

if((x==1)||(x==0)) {
   return(x);
}else {
   return(fib(x-1)+fib(x-2));
}

在该main()方法中,用户输入并fib()调用了多个术语。斐波那契系列打印如下。

cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
   cout << " " << fib(i);
   i++;
}