43 递归的思想与应用(上)
原文:https://www.cnblogs.com/wanmeishenghuo/p/9677857.html参考狄泰软件相关教程
#include <iostream> #include <cstring> #include "DTString.h" using namespace std; using namespace DTLib; unsigned int sum(unsigned int n) { if( n > 1 ) { return n + sum(n - 1); } else { return 1; } } int main() { cout << sum(100) << endl; return 0; }
#include <iostream> #include <cstring> #include "DTString.h" using namespace std; using namespace DTLib; unsigned int sum(unsigned int n) { if( n > 1 ) { return n + sum(n - 1); } else { return 1; } } unsigned int fac(unsigned int n) { if( n > 2 ) { return fac(n - 1) + fac(n - 2); } if( (n == 2) || (n == 1) ) { return 1; } return 0; } int main() { cout << sum(100) << endl; for(int i = 1; i <= 10; i++) { cout << i << " : " << fac(i) << endl; } return 0; }
#include <iostream> #include <cstring> #include "DTString.h" using namespace std; using namespace DTLib; unsigned int sum(unsigned int n) { if( n > 1 ) { return n + sum(n - 1); } else { return 1; } } unsigned int fac(unsigned int n) { if( n > 2 ) { return fac(n - 1) + fac(n - 2); } if( (n == 2) || (n == 1) ) { return 1; } return 0; } unsigned int _strlen_(const char* s) { if( *s != '\0' ) { return 1 + _strlen_(s+1); } else { return 0; } } int main() { cout << _strlen_("Hello World") << endl; return 0; }
代码改进:
unsigned int _strlen_(const char* s) { return s ? (*s ? (1 + _strlen_(s + 1)) : 0) : 0; }
小结:
posted on 2020-08-11 19:55 lh03061238 阅读(79) 评论(0) 编辑 收藏 举报