天天看點

Day_2

       下面是關于遞歸的例子:

      遞歸找了個簡單的1到n求和的例子,遞歸我的了解是每次做到快出結果的時候儲存pc指針到堆棧中,去調用自己接着同樣一件事情,隻是參數變化了,也就是重複的函數操作,占用的記憶體比循環大的多,但是寫法簡單。昨天寫的find查找函數也可以寫成遞歸形式,如下。

      遞歸的幾個基本準則:

1)有一個基準情形,必須有些基準的情形,不然就不能使用遞歸!

2)不斷推進,對于那些要被遞歸求解的情形,遞歸調用必須總能夠朝着一個基準情形推進!  

3)設計法則,證明自己的遞歸各個情況下都是正确的。

void printOut(int n)
{
    if(n >= 10)
        printOut( n/10 );
    cout << (n % 10) << endl;
}
           
#include "main.h"
#include <iostream>
#include <cstdlib>
#include <assert.h>
using namespace std;
int calculate(int m)
{
    // Inlet parameters judgemant
    if(m < 0)
        return -1;
    if( m == 0)
        return 0;
    else
        return calculate(m-1) + m;
}

template<typename type>
int _find(type index, type array[], type length, type value)
{
    if( NULL == array || length == 0 )
        return -1;
    if( value == array[index])
        return index;
    return _find( index + 1, array, length, value );
}

void test()
{
    int array[10] = {1, 2, 3, 4};
    assert(3 == _find<int>(0, array, 10, 4));
}
int main()
{
    int sum;
    sum = calculate(10);
    cout << "sum: " << sum  << endl;
    test();
    return 0;
}
           

繼續閱讀