前言
以下的一些內容大部份是跟大爺的不歸路有關,對沒有興趣的鄉親來說可能會有點無聊,有點悶。
如果有高手不小心路過此地,還望多多指教,如果內容有誤,還麻煩指點一下大爺!感恩!
接下來就是重頭戲啦,費式級數的遞迴解法。其實這些東西在高手面前都只是「小兒科」,都只能算是「入門級」的
但為什麼大爺要搞這些哩,最重要的一點就是當年大爺還在學校的時候,雖然有學到這些演算法,但真正實際去演算倒是很少。
而且大爺好一陣子沒寫程式、但又想重操舊業、再度下海,就順便再複習一下這些東西,也可以練練程式,看能不能發現以前沒注意到的東西囉 ^^"
首先先來討論一下關於「遞迴」這個東西。要寫遞迴真的還不是那麼容昜的,除了本身的「邏輯觀念」要很強之外,「數學底子」也得夠硬,否則光是將問題的公式找出來都辨不到了,也沒辨法將數學再轉換成程式邏輯,寫出程式來,雖然說遞迴它本身還是有些壞處,甚至有程式語言乾脆就不提供,但用它寫出來的程式是真的「比較簡潔」、「也比較美」。不過這種美也只能「孤芳自賞」了
好啦,接下來讓我們來看看遞迴的執行狀況吧,很簡單的一隻小程式
/* Program Description
名稱:rabbit_recursive
版本:0.1版
作者:ckw
日期:2009/08/07
程式目的:
十三世紀的義大利數學家費伯納西 (Fibonacci) 寫了一本商用的算術和代數手冊《Liber abacci》。
在這本書裏,他提出了這麼一個有趣的問題:假定一對兔子在它們出生整整兩個月以後可以生一對小兔子,
其後每隔一個月又可以再生一對小兔子。假定現在在一個籠子裡有一對剛生下來的小兔子,請問一年以後籠子裏應該有幾對兔子?
程式說明:
在第一對兔子未滿2歲之前是無法生下小兔子,所以一開始前2個月免子的數量為1,到第三個月之後,才會開始增加。所以演算法
會從第三個月開始計算。
*/
#include <iostream>
using namespace std;
/*
方法定義
rabbis function
程式目的: count rabbits amoung and return
傳回值:unsigned long 當月的總數
傳入值:
unsigned long amount 儲存本月份總共的兔子數量;
unsigned long presentRabbits 目前的兔子數量
unsigned long lastMonthOriginalRabbits 上個月份未增加前的數量
*/
unsigned long rabbits(unsigned long presentRabbits, unsigned long lastMonthOriginalRabbits, int userInputMonth, int countMonth);
int main(){
int month=0;//記錄使用者輸入的月份值
cout<<"please input the month (you want to know the rabbits amount):";
cin >> month; //讀取使用者輸入的月份
rabbits(1,1,month,1);//呼叫遞迴函數
return (0);
}
/*
方法實作
rabbis function
程式目的: count rabbits amoung and return
傳回值:unsigned long 當月的總數
傳入值:
unsigned long amount 儲存本月份總共的兔子數量;
unsigned long presentRabbits 目前的兔子數量
unsigned long lastMonthOriginalRabbits 上個月份未增加前的數量
*/
unsigned long rabbits(unsigned long presentRabbits, unsigned long lastMonthOriginalRabbits, int userInputMonth, int countMonth){
if(countMonth <=2 && countMonth <= userInputMonth){ //當輸入的月份為1月和2月
cout <<"\n The amount of rabbit of month " << countMonth << " is: 1 \n";
return rabbits(presentRabbits,lastMonthOriginalRabbits,userInputMonth,countMonth+1);
}
else if(countMonth <= userInputMonth ){
cout <<"\n The amount of rabbit of month " << countMonth << " is:" << presentRabbits + lastMonthOriginalRabbits << "\n";
return rabbits(presentRabbits + lastMonthOriginalRabbits,presentRabbits,userInputMonth,countMonth+1); //執行遞迴運算
}
}
以下是執行的過程和結果:
please input the month (you want to know the rabbits amount):12
The amount of rabbit of month 1 is:1
The amount of rabbit of month 2 is:1
The amount of rabbit of month 3 is:2
The amount of rabbit of month 4 is:3
The amount of rabbit of month 5 is:5
The amount of rabbit of month 6 is:8
The amount of rabbit of month 7 is:13
The amount of rabbit of month 8 is:21
The amount of rabbit of month 9 is:34
The amount of rabbit of month 10 is:55
The amount of rabbit of month 11 is:89
The amount of rabbit of month 12 is:144
大爺說:
這個程式其實還存在著一個潛藏的問題,因為大爺是宣告成「無符號長整數」,所以一但數值超出變數的範圍(4294967295)時就會出錯,不過重點不在這,所以大爺就沒有改了 ^^"
好了,看了以上的程式之後,如果有鄉親發現這個程式有任何的地方是錯的,還望鄉親告訴大爺,感恩哩 ^^!
留言列表