Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

R 函数递归


递归

R 也支持函数递归,这意味着一个定义的函数可以调用自身。

递归是一个常见的数学和编程概念。它意味着一个函数调用自身。这样做的好处是可以循环遍历数据以达到结果。

开发人员在使用递归时应格外小心,因为很容易不小心编写出永不终止的函数,或者使用过量内存或处理器资源的函数。但是,如果编写正确,递归可以成为一种非常高效且数学上优雅的编程方法。

在这个例子中,tri_recursion() 是我们定义的一个函数,它调用自身(“递归”)。我们使用 k 变量作为数据,每次递归时它都会递减(-1)。当条件不再大于 0(即为 0 时),递归结束。

对于新手开发者来说,可能需要一些时间才能弄清楚它是如何工作的,最好的方法是通过测试和修改来了解它。

示例

tri_recursion <- function(k) {
  if (k > 0) {
    result <- k + tri_recursion(k - 1)
    print(result)
  } else {
    result = 0
    return(result)
  }
}
tri_recursion(6)
亲自尝试 »

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.