Possible Duplicates:
Calculating large factorials in C++
Howto compute the factorial of x
如何在 C++ 中实现阶乘函数?我的意思是使用适用于 C++ 中的通用数学库的任何参数检查和错误处理逻辑来正确实现它。
最佳答案
递归:
unsigned int factorial(unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
迭代:
unsigned int iter_factorial(unsigned int n)
{
unsigned int ret = 1;
for(unsigned int i = 1; i <= n; ++i)
ret *= i;
return ret;
}
编译时间:
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
}
关于c++ - 你如何在 C++ 中实现阶乘函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5721796/