Home php教程 php手册 php递归函数三种实现方法及如何实现数字累加

php递归函数三种实现方法及如何实现数字累加

Jun 06, 2016 pm 07:48 PM
recursive function

实现递归函数有哪些方法呢?如何用递归函数实现数字累加?这篇文章就主要介绍php递归函数三种实现方法及如何实现数字累加,需要的朋友可以参考下。

      递归函数在编程中是比较常用的一类函数,其特点是函数自身可以调用自身,但是必须在调用自身前有条件判断,否则会导致无限调用下去。本文列出了三种递归函数实现方法,第一种利用引用做参数,第二种利用全局变量,第三种利用静态变量,理解此类问题需要有点基础,包括对全局变量,引用,静态变量的理解,也需对他们的作用范围有所理解。在这不废话了,具体介绍请看下文。

第一种方法:利用引用做参数

  先不管引用做不做参数,必须先明白引用到底是什么?引用不过是指两个不同名的变量指向同一块存储地址。本来每个变量有各自的存储地址,赋值删除各行其道。

现在可好,两个变量共享一块存储地址。 $a=&$b; 。实际上指的是 $a 不管不顾自己原来的存储地址,非要和 $b 共享一室了。因而任何对存储地址数值的改变都会影响两个值。  

  函数之间本来也是各行其是,即便是同名函数。递归函数是考虑将引用作为参数,成为一个桥梁,形成两个函数间的数据共享。虽然两个函数见貌似操作的是不同地址,但是实际上操作的是一块儿内存地址。

复制代码 代码如下:


function test($a=0,&$result=array()){
$a++;
if ($a     $result[]=$a;
    test($a,$result);
}
echo $a;
return $result;
}

  上面的例子非常简答,以a 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 ) 。

        本例比较有意思的是echo a 的值。相信很多人认为是12345678910吧,其实不然,是1098765432。为什么呢?因为函数还没执行echo a前就进行了下一次的函数递归。

        真正执行echo a是当a

第二种方法:利用全局变量

  利用全局变量完成递归函数,,请确保你确实理解什么是全局变量。global在函数内申明变量不过是外部变量的同名引用。变量的作用范围仍然在本函数范围内。改变这些变量的值,外部同名变量的值自然也改变了。但一旦用了&,同名变量不再是同名引用。利用全局变量实现递归函数没必要理解到这么深的一层,还保持原有对全局变量的看法就可以顺理成章理解递归函数。

复制代码 代码如下:


function test($a=0,$result=array()){
    global $result;
    $a++;
    if ($a         $result[]=$a;
        test($a,$result);
    }
    return $result;
}

第三种方法:利用静态变量

  我们常常在类中见到static,今天我们把它利用到递归函数中。请记住static的作用:仅在第一次调用函数的时候对变量进行初始化,并且保留变量值。

  举个栗子:

复制代码 代码如下:


function test(){
static $count=0;
echo $count;
$count++;
}
test();
test();
test();
test();
test();

  

        请问这一段代码的执行结果是多少?是00000么?必然不是。是01234。首先第一次调用test(),static对 $count 进行初始化,其后每一次执行完都会保留 $count 的值,不再进行初始化,相当于直接忽略了 static $count=0; 这一句。

  因而将static应用到递归函数作用可想而知。在将需要作为递归函数间作为“桥梁"的变量利用static进行初始化,每一次递归都会保留"桥梁变量"的值。

复制代码 代码如下:


function test($a=0){
    static $result=array();
    $a++;
    if ($a         $result[]=$a;
        test($a);
    }
    return $result;
}

 

 总结

  所谓递归函数,重点是如何处理函数调用自身是如何保证所需要的结果得以在函数间合理"传递",当然也有不需要函数之间传值得递归函数,例如:

复制代码 代码如下:


function test($a=0){
    $a++;
    if ($a         echo $a;

        test($a);
    }
}

  下面通过一段代码演示一下php使用递归函数实现数字累加的方法。

代码如下所示:

复制代码 代码如下:


function summation ($count) {
   if ($count != 0) :
     return $count + summation($count-1);
   endif;
}
$sum = summation(10);
print "Summation = $sum";
?>

         面对php递归函数,不必要伤脑筋,深入的理解变量引用相关知识对解决此类问题很有帮助,以上内容就是php递归函数三种实现方法及如何实现数字累加的全部内容,希望对大家今后的学习有所帮助。

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

What are the optimization techniques for C++ recursive functions? What are the optimization techniques for C++ recursive functions? Apr 17, 2024 pm 12:24 PM

To optimize the performance of recursive functions, you can use the following techniques: Use tail recursion: Place recursive calls at the end of the function to avoid recursive overhead. Memoization: Store calculated results to avoid repeated calculations. Divide and conquer method: decompose the problem and solve the sub-problems recursively to improve efficiency.

How to solve the excessive function nesting error in Python code? How to solve the excessive function nesting error in Python code? Jun 25, 2023 pm 12:35 PM

Python is a very powerful programming language, and many programmers choose Python as their main programming language. However, too much function nesting in the code can make the program difficult to maintain and understand. This article will explore how to solve the excessive function nesting error in Python code. A brief introduction to function nesting Function nesting refers to the process of defining another function in the body of a function. Function nesting can make the structure of the program clearer and the code easier to read and maintain. However, too many nested functions can lead to an overly complex code structure.

Application of C++ recursive functions in search algorithms? Application of C++ recursive functions in search algorithms? Apr 17, 2024 pm 04:30 PM

Recursive functions are used in search algorithms to explore tree-like data structures. Depth-first search uses a stack to explore nodes, while breadth-first search uses a queue to traverse layer by layer. In practical applications, such as finding files, recursive functions can be used to search for a given file in a specified directory.

What are the exit conditions for a recursive function in C++? What are the exit conditions for a recursive function in C++? Apr 17, 2024 am 11:33 AM

The exit conditions of C++ recursive functions include: Baseline conditions: Check whether the function reaches a state that can directly return results, usually judging whether a certain condition or parameter value meets the threshold. Recursion termination condition: Alternative to or in addition to the baseline condition, ensuring that the function stops after a certain number of recursive calls, by tracking the recursion depth or setting a maximum recursion depth limit.

Application of C++ recursive function in sorting algorithm? Application of C++ recursive function in sorting algorithm? Apr 17, 2024 am 11:06 AM

The application of recursive functions in sorting algorithms in C++ The insertion sort and merge sort algorithms implemented by recursive functions can decompose complex problems into smaller sub-problems and solve them efficiently through recursive calls. Insertion sort: Sorts an array by inserting elements one by one. Merge sort: Divide and conquer, split the array and recursively sort the sub-arrays, and finally merge the sorted sub-arrays.

How to implement the tail recursion optimization strategy of C++ recursive functions? How to implement the tail recursion optimization strategy of C++ recursive functions? Apr 17, 2024 pm 02:42 PM

The tail recursion optimization strategy effectively reduces the function call stack depth and prevents stack overflow by converting tail recursive calls into loops. Optimization strategies include: Detect tail recursion: Check whether there are tail recursive calls in the function. Convert functions into loops: Use loops instead of tail-recursive calls and maintain a stack to save intermediate state.

How to implement factorial using recursive functions in Go language? How to implement factorial using recursive functions in Go language? Jul 31, 2023 pm 08:31 PM

How to implement factorial using recursive functions in Go language? Factorial is a common calculation in mathematics that multiplies a non-negative integer n by all positive integers smaller than it, up to 1. For example, the factorial of 5 can be expressed as 5!, calculated as 54321=120. In computer programming, we often use recursive functions to implement factorial calculations. First, we need to understand the concept of recursive functions. A recursive function refers to the process of calling the function itself within the definition of the function. When solving a problem, a recursive function will continually

C program to list all files and subdirectories in a directory C program to list all files and subdirectories in a directory Aug 25, 2023 pm 10:09 PM

Here we have a directory. Our task is to create a C program to list all files and subdirectories in a directory. A directory is a place/area/location where a set of file(s) will be stored. A subdirectory is a directory within the root directory, which, in turn, can have another subdirectory. In C programming language you can easily list all files and subdirectories in a directory. The following program shows how to list all files and subdirectories in a directory. //C program example to list all files and subdirectories in the directory Live demonstration #include<stdio.h>#include<dirent.h>intmain(void){ &am

See all articles