用循环和递归分别计算阶乘
2012-03-21 20:27
232 查看
// factor.c -- uses loops and recursion to calculate factorials #include <stdio.h> long fact(int n); long rfact(int n); int main(void) { int num; printf("This program calculates factorials.\n"); printf("Enter a value in the range 0-12 (q to quit):\n"); while (scanf("%d", &num) == 1) { if (num < 0) printf("No negative numbers, please.\n"); else if (num > 12) printf("Keep input under 13.\n"); else { printf("loop: %d factorial = %ld\n", num, fact(num)); printf("recursion: %d factorial = %ld\n", num, rfact(num)); } printf("Enter a value in the range 0-12 (q to quit):\n"); } printf("Bye.\n"); return 0; } long fact(int n) // loop-based function { long ans; for (ans = 1; n > 1; n--) ans *= n; return ans; } long rfact(int n) // recursive version { long ans; if (n > 0) ans= n * rfact(n-1); else ans = 1; return ans; }
相关文章推荐
- 循环计算和递归计算阶乘
- C语言用分别用递归和循环求数字的阶乘的方法
- #DayOne#,分别用循环和递归的方式实现阶乘
- 计算0~10的阶乘 使用递归
- 使用java计算一个数的阶乘--递归
- 利用递归计算N的阶乘
- 递归求阶乘和循环阶乘
- 递归计算阶乘
- 计算阶乘(递归与迭代)
- 循环与递归求阶乘
- 计算二项式系数使用循环和递归实现
- 递归计算阶乘
- for循环计算阶乘
- 递归计算阶乘
- 编程作业50页3题 分别使用 do-while和 for 循环计算1+1/2!+1/3!+1/4!...+1/20!
- JavaScript使用递归和循环实现阶乘的实例代码
- 用递归方法计算n的阶乘n
- 阶乘尾部零的个数,递归计算
- 9.10 编写并测试Fibonacii函数,该函数用循环代替递归计算斐波那契数。
- 28、利用递归计算自然数 n 的阶乘