C中的阶乘使用递归 [英] Factorial using recursion in C

查看:76
本文介绍了C中的阶乘使用递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道这个程序

int fact(int n)
{
  if(n==0)  
    return(1);

  return(n*fact(n-1));
}

但是我不清楚内在是如何发生的?

But what is not clear to me is how the inner thing is happening?

如何计算5*4*3*2*1(如果n为5)

How is it calculating 5*4*3*2*1 (if n is 5)

请对此进行清楚的解释.

Please give a clear explanation on this.

谢谢.....

推荐答案

在数学上,阶乘的递归定义可以像这样递归表示(来自

Mathematically, the recursive definition of factorial can be expressed recursively like so (from Wikipedia):

使用==表示等效性,请考虑这对于n = 3的工作原理:

Consider how this works for n = 3, using == to mean equivalence:

3! == 2! * 3 == (1! * 2) * 3 == ((1) * 2) * 3

这可以通过重复应用递归规则来纯粹从符号上推导.

This can be derived purely symbolically by repeatedly applying the recursive rule.

此定义的作用是首先将给定的阶乘扩展为等效的乘法系列.然后,它执行实际的乘法运算.您拥有的C代码执行的方式完全相同.

What this definition does is first expand out a given factorial into an equivalent series of multiplications. It then performs the actual multiplications. The C code you have performs the exact same way.

这篇关于C中的阶乘使用递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆