你如何在 C++ 中实现阶乘函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5721796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you implement the factorial function in C++?
提问by Jonathan Allen
Possible Duplicates:
Calculating large factorials in C++
Howto compute the factorial of x
可能的重复:
在 C++ 中计算大阶乘
如何计算 x 的阶乘
How do you implement the factorial function in C++? And by this I mean properly implement it using whatever argument checking and error handling logic is appropriate for a general purpose math library in C++.
你如何在 C++ 中实现阶乘函数?我的意思是使用任何适合 C++ 通用数学库的参数检查和错误处理逻辑来正确实现它。
回答by Hovhannes Grigoryan
Recursive:
递归:
unsigned int factorial(unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
Iterative:
迭代:
unsigned int iter_factorial(unsigned int n)
{
unsigned int ret = 1;
for(unsigned int i = 1; i <= n; ++i)
ret *= i;
return ret;
}
Compile time:
编译时间:
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
回答by Cubbi
Besides the obvious loops and recursions, modern C++ compilers support the gamma function as tgamma()
, closely related to factorial:
除了明显的循环和递归之外,现代 C++ 编译器还支持 gamma 函数 as tgamma()
,与 factorial 密切相关:
#include <iostream>
#include <cmath>
int main()
{
int n;
std::cin >> n;
std::cout << std::tgamma(n+1) << '\n';
}
test run: https://ideone.com/TiUQ3
试运行:https: //ideone.com/TiUQ3
回答by yasouser
You might want to take a look at boost/math/special_functions/factorials.hpp
if you have Boost installed. You can read about it at: Boost Factorial
您可能想看看boost/math/special_functions/factorials.hpp
是否安装了 Boost。您可以在以下位置阅读:Boost Factorial