下面是关于递归的例子:
递归找了个简单的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; }