zoukankan      html  css  js  c++  java
  • 第四十三课 递归的思想与应用(上)

     

     1 #include <iostream>
     2 #include <cstring>
     3 #include "DTString.h"
     4 
     5 using namespace std;
     6 using namespace DTLib;
     7 
     8 unsigned int sum(unsigned int n)
     9 {
    10     if( n > 1 )
    11     {
    12         return n + sum(n - 1);
    13     }
    14     else
    15     {
    16         return 1;
    17     }
    18 }
    19 
    20 int main()
    21 {
    22     cout << sum(100) << endl;
    23 
    24     return 0;
    25 }

     1 #include <iostream>
     2 #include <cstring>
     3 #include "DTString.h"
     4 
     5 using namespace std;
     6 using namespace DTLib;
     7 
     8 unsigned int sum(unsigned int n)
     9 {
    10     if( n > 1 )
    11     {
    12         return n + sum(n - 1);
    13     }
    14     else
    15     {
    16         return 1;
    17     }
    18 }
    19 
    20 unsigned int fac(unsigned int n)
    21 {
    22     if( n > 2 )
    23     {
    24         return fac(n - 1) + fac(n - 2);
    25     }
    26 
    27     if( (n == 2) || (n == 1) )
    28     {
    29         return 1;
    30     }
    31 
    32     return 0;
    33 }
    34 
    35 int main()
    36 {
    37     cout << sum(100) << endl;
    38 
    39     for(int i = 1; i <= 10; i++)
    40     {
    41         cout << i << " : " << fac(i) << endl;
    42     }
    43 
    44     return 0;
    45 }

     1 #include <iostream>
     2 #include <cstring>
     3 #include "DTString.h"
     4 
     5 using namespace std;
     6 using namespace DTLib;
     7 
     8 unsigned int sum(unsigned int n)
     9 {
    10     if( n > 1 )
    11     {
    12         return n + sum(n - 1);
    13     }
    14     else
    15     {
    16         return 1;
    17     }
    18 }
    19 
    20 unsigned int fac(unsigned int n)
    21 {
    22     if( n > 2 )
    23     {
    24         return fac(n - 1) + fac(n - 2);
    25     }
    26 
    27     if( (n == 2) || (n == 1) )
    28     {
    29         return 1;
    30     }
    31 
    32     return 0;
    33 }
    34 
    35 unsigned int _strlen_(const char* s)
    36 {
    37     if( *s != '' )
    38     {
    39         return 1 + _strlen_(s+1);
    40     }
    41     else
    42     {
    43         return 0;
    44     }
    45 }
    46 
    47 int main()
    48 {
    49     cout << _strlen_("Hello World") << endl;
    50 
    51     return 0;
    52 }

     代码改进:

    1 unsigned int _strlen_(const char* s)
    2 {
    3     return s ? (*s ? (1 + _strlen_(s + 1)) : 0) : 0;
    4 }

    小结:

  • 相关阅读:
    快速入门:BUMO 节点安装运维指南
    快速入门:BUMO 智能合约(hello world)
    python 多进程处理 multiprocessing模块
    python 多进程处理 multiprocessing模块
    python 多进程处理 multiprocessing模块
    一段简单的数据加密小例程
    一段简单的数据加密小例程
    一段简单的数据加密小例程
    一段简单的数据加密小例程
    家用PC机打造VSphere5.1 测试环境:之部署VCenter Server 5.1
  • 原文地址:https://www.cnblogs.com/wanmeishenghuo/p/9677857.html
Copyright © 2011-2022 走看看