Home php教程 php手册 对函数及递归的通俗理解

对函数及递归的通俗理解

Jun 13, 2016 am 10:55 AM
function Can Base right Compare understand of output return recursion difficult

没有基础的兄弟可能对函数的递归比较难以理解,特别是递归里返回输出的概念理不清,是如何返回的。

下面是课本上的列子,就拿出来,用我的理解来做解释。希望能帮到对这块还没弄懂的兄弟。

    function test($n){

        echo $n."nbsp";        

        if($n>0){

            test($n-1);//调用函数本身。

        }else{

            echo "";

        }

        echo $n."$nbsp";

    }

    test(3);//调用函数输出。

?>

得到结果是 3  2  1  0     0  1  2  3

大家比较容易理解的是前面输出的3  2  1  0  但对于后面的 0  1  2   3 为什么输出不是很清楚。

要理解这个递归的回归输出先要弄清楚,什么是函数,

 

官方解释:

         函数(function)是一段完成指定任务的已命名代码块。

使用函数的理由中有一条是:

         可提高程序的重用性

重用性就是可以重复使用,不多次编写相同代码。 就是将程序中重复编写的代码写成函数,然后在其他多处需要使用时只用调用函数名就可使用,而不用再次重复编写相同代码。

通俗简单点讲,函数就是一段已经写好的代码一把已经造好的枪,然后将它放在了公共仓库里,

不同功能的函数都有自己的名字【function 函数名(){}】,如同不同功能的枪也有自己的名字,如来福枪,狙击枪,手枪等,这些取好名的函数和枪都已经编写好,造好,放在仓库。

然后有谁想使用某个功能的函数时,到这个仓库里喊这个函数的名字【函数名()】,就将函数拿了出来使用,如同警察依据任务的不同要求到仓库里拿不同功能的枪一样。

————这就是函数的定义。

函数的使用:

                官方的叫法就是:调用   如  aaa();

               通俗的理解就是:那个谁谁谁(叫函数的名字)过来这里,把交给你的代码给我在这个位置写一遍。

我的理解是,就是是替换,函数的调用就是一个占位符,遇到了这个占位符【aaa()】就替换成这个占位符【aaa()】指定的已经写好的函数里的代码。遇到就替换,然后程序继续按先后的顺序往下执行。

具体例子说明:

/*=============装函数(手枪)的仓库=======================*/

function test($n){

        echo $n."nbsp";        

        if($n>0){

            test($n-1);//调用函数本身。

        }else{

            echo "";

        }

        echo $n."$nbsp";

    }

 

/*=============装函数(手枪)的仓库======================*/

 

test(3);     //调用函数,按我的想的就是遇到了占位符了,要替换名字叫test的那个函数里的代码,(你也可以理解成到仓库里拿叫test的枪装入3发子弹)

于是test(3)第一次遇到变成了

/***********************第一次调用时替换************************/

  echo $n."nbsp";        //这个时候$n=3  子弹是三发

        if($n>0){          //判断$n为3大于0 , 执行下边的

            test($n-1);     //再次遇到调用函数,遇到就替换,(子弹打出去一发)

        }else{

            echo "";  //不执行

        }

        echo $n."$nbsp"; //  这个时候$n=3,所以输出3

/***********************第一次调用时替换************************/

/***********************第二次调用时替换************************/

echo $n."nbsp";        //这个时候$n=3  子弹是三发

            if($n>0){          //判断$n>3 执行下边的

                 echo $n."nbsp";        //这个时候$n=2  子弹是二发

                           if($n>0){          //判断$n为2大于0, 执行下边的                                   

                               test($n-1);     //再次遇到调用函数,遇到就替换,(子弹再打出去一发)

                           }else{

                                 echo "";  //不执行

                           }

                                echo $n."$nbsp";//这个时候$n=2,所以输出2

        }else{

            echo "";  //不执行

        }

        echo $n."$nbsp";  //这个时候$n=3,所以输出3

/***********************第二次调用时替换************************/

/***********************第三次调用时替换************************/

echo $n."nbsp";        //这个时候$n=3  子弹是三发

            if($n>0){          //判断$n>3 执行下边的

                 echo $n."nbsp";        //这个时候$n=2  子弹是二发

                           if($n>0){          //判断$n为2大于0, 执行下边的                          

                                  echo $n."nbsp";        //这个时候$n=1  子弹是一发

                                   if($n>0){          //判断$n为1 大于0, 执行下边的

                                          test($n-1);     //再次遇到调用函数,遇到就替换,(子弹打出去一发)

                                   }else{

                                          echo "";  //不执行

                                 }

                                     echo $n."$nbsp"; //  这个时候$n=1,所以输出1                        

                           }else{

                                 echo "";  //不执行

                           }

                                echo $n."$nbsp";//这个时候$n=2,所以输出2

        }else{

            echo "";  //不执行

        }

        echo $n."$nbsp";  //这个时候$n=3,所以输出3

/***********************第三次调用时替换************************/

/***********************第四次调用时替换************************/

echo $n."nbsp";        //这个时候$n=3  子弹是三发

            if($n>0){          //判断$n>3 执行下边的

                 echo $n."nbsp";        //这个时候$n=2  子弹是二发

                           if($n>0){          //判断$n为2大于0, 执行下边的                          

                                  echo $n."nbsp";        //这个时候$n=1  子弹是一发

                                   if($n>0){          //判断$n为1 大于0, 执行下边的

                                          

                                        echo $n."nbsp";        //这个时候$n=0  子弹是0发

                                             if($n>0){          //判断$n为0等于0 ,不执行下边的

                                                     test($n-1);     //因为不执行所以就不替换了。

                                            }else{

                                                    echo "";  //输出

                                           }

                                    echo $n."$nbsp"; //  这个时候$n=0,所以输出0

                                  }else{

                                          echo "";  //不执行

                                 }

                                     echo $n."$nbsp"; //  这个时候$n=1,所以输出1                         

                           }else{

                                 echo "";  //不执行

                           }

                                echo $n."$nbsp";//这个时候$n=2,所以输出2

        }else{

            echo "";  //不执行

        }

        echo $n."$nbsp";  //这个时候$n=3,所以输出3

/***********************第四次调用时替换************************/

/*##################最终得到只有if判断语句和基础表达式组成的代码###########################*/

    test(3);//在最开始的时候只调用一次替换;

    //$n=3

    echo $n."nbsp";//输出3    

        if($n>0){

        //test(3-1)替成了下面的

                echo $n."nbsp";//输出2

                if($n>0){

                //test(2-1)替成了下面的

                        echo $n."nbsp";//输出1                    

                        if($n>0){

                                    //test(1-1)替成了下面的

                                    echo $n."nbsp";//输出0    

                                    if($n>0){//判断执行

                                    //test()没有替换

                                        test($n-1);//不执行 因为不大约0

                                    }else{

                                        echo "";//输出

                                    }

                                    echo $n."$nbsp";//输出0

                        }else{

                            echo "";//不执行

                        }

                        echo $n."$nbsp";//输出1

                }else{

                    echo "";//不执行

                }

                echo $n."$nbsp";//输出2

        }else{

            echo "";////不执行

        }

        echo $n."$nbsp";//输出3    

/*##################最终得到###########################*/

按照最终得到的代码依次输出的结果就是

输出结果就是 3 2  1 0 0 1  2  3

函数和递归的使用,最终就是解析成上面的代码执行的,

这就是我理解的函数,以及递归,用一句话说:“本来江湖上是没有递归的,出现的函数多了,也就有了递归。”

一点简单的理解,希望能帮助没有基础的兄弟理解函数,理解递归,最终形成自己的理解自己的想法和思路

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

Detailed explanation of C++ function recursion: application of recursion in string processing Detailed explanation of C++ function recursion: application of recursion in string processing Apr 30, 2024 am 10:30 AM

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

A beginner's guide to C++ recursion: Building foundations and developing intuition A beginner's guide to C++ recursion: Building foundations and developing intuition May 01, 2024 pm 05:36 PM

Recursion is a powerful technique that allows a function to call itself to solve a problem. In C++, a recursive function consists of two key elements: the base case (which determines when the recursion stops) and the recursive call (which breaks the problem into smaller sub-problems ). By understanding the basics and practicing practical examples such as factorial calculations, Fibonacci sequences, and binary tree traversals, you can build your recursive intuition and use it in your code with confidence.

C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application Apr 30, 2024 am 10:45 AM

Tail recursion optimization (TRO) improves the efficiency of certain recursive calls. It converts tail-recursive calls into jump instructions and saves the context state in registers instead of on the stack, thereby eliminating extra calls and return operations to the stack and improving algorithm efficiency. Using TRO, we can optimize tail recursive functions (such as factorial calculations). By replacing the tail recursive call with a goto statement, the compiler will convert the goto jump into TRO and optimize the execution of the recursive algorithm.

Detailed explanation of C++ function recursion: tail recursion optimization Detailed explanation of C++ function recursion: tail recursion optimization May 03, 2024 pm 04:42 PM

Recursive definition and optimization: Recursive: A function calls itself internally to solve difficult problems that can be decomposed into smaller sub-problems. Tail recursion: The function performs all calculations before making a recursive call, which can be optimized into a loop. Tail recursion optimization condition: recursive call is the last operation. The recursive call parameters are the same as the original call parameters. Practical example: Calculate factorial: The auxiliary function factorial_helper implements tail recursion optimization, eliminates the call stack, and improves efficiency. Calculate Fibonacci numbers: The tail recursive function fibonacci_helper uses optimization to efficiently calculate Fibonacci numbers.

C++ function recursion explained: alternatives to recursion C++ function recursion explained: alternatives to recursion May 01, 2024 pm 04:54 PM

Recursion is a technique where a function calls itself, but has the disadvantages of stack overflow and inefficiency. Alternatives include: tail-recursion optimization, where the compiler optimizes recursive calls into loops; iteration, which uses loops instead of recursion; and coroutines, which allow execution to be paused and resumed, simulating recursive behavior.

See all articles