zoukankan      html  css  js  c++  java
  • 递归函数recursion

      1(调用自身)递归函数是‘自己调用自己‘的函数,不管这样的调用是直接的还是间接的。

      2(递归出口)因为函数不可以一直调用自己,无法停止工作,所以递归函数一定具备结束条件。

    http://www.cnblogs.com/emanlee/archive/2009/05/05/1449596.html

    函数递归调用示例(教材习题5.3,运行结果012345)

    #include<stdio.h> 
    void fun(int k); 
    void main() 
    {  
         int w=5;   fun(w); 
    }
    
    void fun(int k) 
    { 
         if(k>0)   fun(k-1); 
         printf("%d",k); 
    }

    3. 实例: 翻转字符串
    --------------------------------------------------------------------------------
    #include <stdio.h>
    
    void revers(char *cs);
    
    int main(void)
    {
        revers("123456789");
    
        getchar();    
        return 0;
    }
    
    void revers(char *cs)
    {
        if (*cs)//检测到‘’时跳出
        { 
            revers(cs + 1);
            putchar(*cs);
        }
    }

    4阶乘

     1 #include <stdio.h>
     2 
     3 int factorial(int num);
     4 
     5 int main(void)
     6 {
     7     int i;
     8     for (i = 1; i <= 9; i++)
     9     printf("%d: %d
    ", i, factorial(i));
    10 
    11     getchar();    
    12     return 0;
    13 }
    14 
    15 int factorial(int num)
    16 {
    17     if (num == 1)
    18         return(1);
    19     else
    20         return(num * factorial(num-1));
    21 }

     5斐波那契数列

     1 //斐波那契
     2 long Fib(int n)
     3 {
     4  if (n == 0) 
     5   return 0;
     6  if (n == 1) 
     7   return 1;
     8  if (n > 1) 
     9   return Fib(n-1) + Fib(n-2);
    10 }

    6汉诺塔

     1 #include <stdio.h>  
     2 //第一个塔为初始塔,中间的塔为借用塔,最后一个塔为目标塔  
     3 int i=1;//记录步数  
     4 void move(int n,char from,char to) //将编号为n的盘子由from移动到to  
     5 {printf("第%d步:将%d号盘子%c---->%c
    ",i++,n,from,to);  
     6 }  
     7 void hanoi(int n,char from,char denpend_on,char to)//将n个盘子由初始塔移动到目标塔(利用借用塔)  
     8 {  
     9     if (n==1)  
    10     move(1,from,to);//只有一个盘子是直接将初塔上的盘子移动到目的地  
    11     else  
    12     {  
    13       hanoi(n-1,from,to,denpend_on);//先将初始塔的前n-1个盘子借助目的塔移动到借用塔上  
    14       move(n,from,to);              //将剩下的一个盘子移动到目的塔上  
    15       hanoi(n-1,denpend_on,from,to);//最后将借用塔上的n-1个盘子移动到目的塔上  
    16     }  
    17 }  
    18 void main()  
    19 {  
    20      printf("请输入盘子的个数:
    ");  
    21      int n;  
    22      scanf("%d",&n);  
    23      char x='A',y='B',z='C';  
    24      printf("盘子移动情况如下:
    ");  
    25      hanoi(n,x,y,z);  
    26 }  

     

  • 相关阅读:
    RabbitMq windows 安装
    JQuery.Ajax()的data参数传递方式
    [转载]ASP.NET中TextBox控件设立ReadOnly="true"后台取不到值
    vue-cli 3.0脚手架搭建项目
    二、操作符
    一、JavaScript基础
    html苹方字体
    js十大排序算法收藏
    iframe高度自适应的6个方法
    CSS3:不可思议的border属性
  • 原文地址:https://www.cnblogs.com/prayer521/p/5754784.html
Copyright © 2011-2022 走看看