1. 程式人生 > >用遞迴的方法編寫函式求斐波那契級數,觀察遞迴呼叫的過程

用遞迴的方法編寫函式求斐波那契級數,觀察遞迴呼叫的過程

#include<iostream>
using namespace std;
int fbn(int n){
	cout<<"呼叫fbn("<<n<<")的過程: "; 
	if(n==1||n==2){
	   cout<<"返回 1"<<endl;
	   return 1;	
	}
	else{
	  cout<<"呼叫fbn("<<n-1<<")和 呼叫fbn("<<n-2<<")"<<endl;	
	  return fbn(n-1)+fbn(n-2);
    }
}
int main(){
	cout<<"請輸入一個數:";
	int n;
	cin>>n;
	cout<<endl<<endl;
	cout<<"最後結果:f("<<n<<")等於"<<fbn(n)<<endl; 
	return 0;
}