C语⾔递归实现n的阶乘(n!)
⾮负整数n的阶乘可以表⽰为n! (读作:n的阶乘),其定义如下:
n! = n·(n - 1)· (n - 2)· …·1 (n⼤于或等于l),且n = 0时,n! = l
例如,5 ! = 5·4·3·2·1 = 120。
请编写⼀个程序,读⼊⼀个⾮负整数,计算并输出其阶乘。
思路: 阶乘 就是每次⽤⾃⼰乘以⾃⼰-1,然后⽤⾃⼰-1在乘⾃⼰-1-1……利⽤递归的性质可以很好的实现这个过程。
#include <stdio.h>
int factorial(int x);
int main(int argc, char const *argv[])
{
int s;
printf("Enter a positive integer:\n");
scanf("%d",&s);
factorial(s);
printf("%d! is %d\n",s,factorial(s));
return 0;
}
int factorial(int x)
{
if (x == 0 )
{
return 1;
c语言用递归函数求n的阶乘
}
else
return x*factorial(x-1);
}
若符合单⼀出⼝原则也可将函数部分更改为
int factorial(int x)
{
int f=0;
if (x == 0 )
{
f=1
return f;
}
else
return f=x*factorial(x-1);
}
牢记递归四条基本法则:
1. 基准情形。必须总有某些基准情形,它⽆须递归就能解出。
2. 不断推进。对于那些需要递归求解的情形,每⼀次递归调⽤都必须要使求解状况朝接近基准情形的⽅向推进
3. 设计法则。假设所有的递归调⽤都能运⾏。
4. 合成效益法则。在求解⼀个问题的同⼀实例时,切勿在不通的递归调⽤中做重复性的⼯作。
(以上四条出⾃《数据结构与算法分析——C语⾔描述版》)