如何在C++中实现阶乘函数?我的意思是使用适用于C++通用数学库的任何参数检查和错误处理逻辑来正确实现它。
可能的重复问题:
在C ++中计算大的阶乘
如何计算x的阶乘
如何在C++中实现阶乘函数?我的意思是使用适用于C++通用数学库的任何参数检查和错误处理逻辑来正确实现它。
可能的重复问题:
在C ++中计算大的阶乘
如何计算x的阶乘
递归:
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++编译器支持伽玛函数作为tgamma()
,与阶乘密切相关:
#include <iostream>
#include <cmath>
int main()
{
int n;
std::cin >> n;
std::cout << std::tgamma(n+1) << '\n';
}
boost::math::factorial
。 - Cubbi如果您已经安装了 Boost,您可能需要查看 boost/math/special_functions/factorials.hpp
。 您可以在以下链接中阅读有关它的信息:Boost 阶乘