LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 250|回复: 0

递归性

[复制链接]
发表于 2024-2-19 22:55:51 | 显示全部楼层 |阅读模式
递归性是函数必须自行调用的属性。它对于某些任务很有用,例如对元素进行排序或计算数字的阶乘。例如,为了获得一个数字()的阶乘,数学公式将是: 更具体地说,(5的阶乘)将是: 在 C++ 中计算此值的递归函数可以是:

n!n! = n * (n-1) * (n-2) * (n-3) ... * 15!5! = 5 * 4 * 3 * 2 * 1 = 120

// factorial calculator
#include <iostream>
using namespace std;

long factorial (long a)
{
  if (a > 1)
   return (a * factorial (a-1));
  else
   return 1;
}

int main ()
{
  long number = 9;
  cout << number << "! = " << factorial (number);
  return 0;
}
9! = 362880


请注意,在函数阶乘中,我们包含了对自身的调用,但前提是传递的参数大于 1,否则,函数将执行无限递归循环,其中一旦达到 0,它将继续乘以所有负数(可能会在运行时的某个时间点引发堆栈溢出)。

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表