當前位置:編程學習大全網 - 編程軟體 - 用遞歸的方法編寫函數求Fibonacci級數,公式為Fn=Fn-1+Fn-2(n>2),F2=F1=1

用遞歸的方法編寫函數求Fibonacci級數,公式為Fn=Fn-1+Fn-2(n>2),F2=F1=1

如下:

#include <iostream>

using namespace std;

int fibonacci(int n);

int main() {

int n;

cout << "請輸入壹個整數(大於2)" << endl;

cin >> n;

cout << "求出的Fibonacci級數為" << fibonacci(n) << endl;

return 0; //這裏把return 3;改成 return 0;

}

int fibonacci(int n)

{

//int F1 = 1;//這裏去掉這壹句

//int F2 = 1;//這裏去掉這壹句

if (n == 1|| n==2)//這裏把終止條件if(n==3)改成if (n == 1|| n==2)

return 1; //這裏把 return 2;改成 return 1;

else

return fibonacci(n - 1) + fibonacci(n - 2);

}

  • 上一篇:山西哪所學校學前教育比較專業?
  • 下一篇:湖南捷行智能系統有限公司怎麽樣?
  • copyright 2024編程學習大全網