用程序解释C语言中的递归函数
递归函数是根据自身定义某事物的过程。它是一个在函数体中再次调用自身的函数。
函数fact(),计算整数'N'的阶乘,它是从1到N的所有整数的乘积。
当以1(或)0为参数调用fact()时,函数返回1。否则,它返回n*fact(n-1)的乘积,这种情况发生直到'n'等于1。
Fact (5) =5* fact (4) =5*4*3* fact (3) =5*4*3*2* fact (2) =5*4*3*2*1 fact (1) =5*4*3*2*1 = 120.
示例
以下是递归函数的C程序-
#include输出结果int main ( ){ int n,f; int fact (int); printf ("enter a number"); scanf ("%d", &n); f= fact (n); printf ("factorial value = %d",f); } int fact (int n){ int f; if ( ( n==1) || (n==0)) return 1; else f= n*fact (n-1); return f; }
执行上述程序时,会产生以下结果-
Enter a number 5 Factorial value = 120