zoukankan      html  css  js  c++  java
  • C语言基础(14)-递归

    一. 递归的定义

    函数可以调用自己,这就叫函数的递归。

    先序递归和后序递归

    #include <stdio.h>
    
    void test(int n);
    void test1(int n);
    
    void main() {
        
        int a = 10;
        test1(a);
        system("pause");
    }
    
    
    void test(int n) {
    
        if (n > 0){ // 递归终止条件,递归一定要有终止条件
            printf("n=%d
    ",n); // 先序递归 输出结果:10 9 8 7 6 5 4 3 2 1
            test1(n-1);
        }
    }
    
    void test1(int n) {
    
        if (n > 0) {
            test1(n-1);
            printf("n=%d
    ",n); // 后序递归 输出结果:1 2 3 4 5 6 7 8 9 10
        }
    
    }

    例1:求第n个人的岁数

    n个人排成一队,问第n个人多少岁,他回答比前面一个人大2岁,再问前面一个人多少岁,他回答比前面一个人大2岁,一直问到最后问第一个人,他回答10

    #include <stdio.h>
    
    int getAge(int n);
    
    void main() {
        
        int a = 8;
        printf("第%d个人的岁数是:%d
    ",a,getAge(a));
        system("pause");
    }
    
    
    int getAge(int n) {
    
        int age;
        if (n == 1) {
            age = 10;
        }
        else{
            age = getAge(n - 1) + 2;
        }
        return age;
    
    }

    例2:将十进制数转化为二进制数

    #include <stdio.h>
    
    int getBinary(int n);
    
    void main() {
        
        int a = 5;
        getBinary(a);
        system("pause");
    }
    
    
    //将十进制数转换为二进制数
    int getBinary(int n) {
    
        int i = n % 2;
        if (n >= 2) {
            getBinary(n / 2);
        }
        printf("%d",i);
    }

    例3:斐波那契数列

    #include <stdio.h>
    
    int fib(int n);
    
    void main() {
        
    
        for (int i = 0; i < 11; i++) {
            printf("第%d项的值为%d
    ", i, fib(i));
        }
    
        system("pause");
    }
    
    
    // 斐波那契数列
    int fib(int n) {
    
        if (n == 0)
            return 0;
        if (n == 1)
            return 1;
        if (n > 1)
            return fib(n - 1) + fib(n - 2);
    
    }

    例4:计算一个字符串的长度

    #include <stdio.h>
    
    
    int mystrlen(const char *p, int n);
    
    void main() {
        
        char *a = "hello123";
        printf("当前字符串的长度为:%d
    ",mystrlen(a,0));
    
        system("pause");
    }
    
    
    int mystrlen(const char *p, int n) {
    
        if (p[n]) { // 这里判断是否到达字符串末尾的0
            return mystrlen(p,n+1);
        }else {
            return n;
        }
    
    }

    例5:求n个自然数的和

    // 求n个自然数的和
    int mysum(int n) {
        if (n == 0) { // 递归终止条件
            return 0;
        }
        return mysum(n - 1) + n;
    }
  • 相关阅读:
    K
    CFileDialog的用法
    MFC编辑框换行实现
    MFC通过对话框窗口句柄获得对话框对象指针
    AfxGetMainWnd()函数用法
    this指针和m_hWnd的区别
    WinAPI: FindWindow、FindWindowEx
    深入浅出Hibernate(二)多对一关系映射
    JAVA 并发编程-读写锁之模拟缓存系统(十一)
    很easy的js双向绑定框架(二):控制器继承
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/6370924.html
Copyright © 2011-2022 走看看