计算 C 语言中求整数阶乘有递归、循环和迭代 3 种方法,对于较小 n 值(n
C 语言中计算阶乘
在 C 语言中,求一个整数的阶乘有以下几种方法:
1. 递归方法
int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } }
2. 循环方法
立即学习“C语言免费学习笔记(深入)”;
int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
3. 迭代方法
int factorial(int n) { int result = 1; while (n > 0) { result *= n; n--; } return result; }
哪种方法更好?
对于较小的 n 值(例如 n
示例
计算 5 的阶乘:
int result = factorial(5); printf("5 的阶乘是 %d\n", result);
输出:
5 的阶乘是 120
以上就是c语言怎么求阶乘的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号