下面是一个阶乘的递归实现。
点击(此处)折叠或打开
- #include <stdio.h>
- int fact(int n)
- {
- if(n < 0){
- printf("the number must be larger than 0\n");
- return -1;
- }
- return n <= 1 ? 1:n*fact(n-1); //n = 1是递归结束条件
- }
- int main()
- {
- int n = 0;
- int total;
- printf("Please input the number:");
- scanf("%d",&n);
- total = fact(n);
- printf("total = %d\n",total);
- return 0;
- }
下面是循环实现,循环不像递归有那么大的函数调用开销,也不用担心栈溢出,注重效率的地方最好用循环代替递归。
点击(此处)折叠或打开
- int main()
- {
- int n = 0;
- int total = 1;
- printf("Please input the number:");
- scanf("%d",&n);
- if(n < 0){
- printf("the number must be larger than 0\n");
- return -1;
- }
- for(; n >= 0; n--){
- if(n == 0)
- break;
- total *=n;
- }
- printf("total = %d\n",total);
- }