如何在c++中计算阶乘
How to calculate factorial in c++
通过函数计算C++中的阶乘
我写了这个代码:
int fact (int A)
{
int B ;
B= A*(A-1);
return B;
}
int main ()
{
int x;
cout <<"Enter number to calulate its factorial :"<<endl;
cin >> x ;
cout << fac (x);
}
在发布之前,你有没有试过用谷歌搜索它?
int factorial(int n)
{
if (n < 0 ) {
return 0;
}
return !n ? 1 : n * factorial(n - 1);
}
事实函数只计算一次阶乘。你应该重新做一些事情,比如:
int fact (int A)
{
if (A <= 1) {
return 1;
}
return A*fact(A-1);
}
或者,如果你想以迭代的方式进行,那么你应该做以下操作:
int fact (int A)
{
int B = 1, i = 2;
for (; i<=A; i++) {
B = B*i;
}
return B;
}
为什么不搜索它呢。
无论如何。。。
int n, count;
unsigned long long int factorial=1;
cout<<"Enter an integer: ";
cin>>n;
if ( n< 0)
printf("Error!!! Factorial of negative number doesn't exist.");
else
{
for(count=1;count<=n;++count) /* for loop terminates if count>n */
{
factorial*=count; /* factorial=factorial*count */
}
cout<<factorial;
}
首先,这与C++无关(正如您的问题所说)。这是特定于alogorithms的,它们可以用在任何语言中。
您可以使用以下示例作为参考。
int fact (int A)
{
if (A == 0) {
return 1;
}
return A*fact(A-1);
}
int factorial (int a) {
return a==0 ? 1 : a*factorial(a-1);
}
由于您使用的是C++而不是C,所以我只使用一个模板函数。额外的好处是:由于在编译时进行了扩展/实现,您的代码将得到高度优化,并且基本上尽可能固定,几乎没有开销:
// First the generic template for pretty much all numbers
template <unsigned int X>
unsigned int factorial() {
return X * factorial<X - 1>();
}
// Now the specialization for the special case of 0
template <>
unsigned int factorial<0>() {
return 1;
}
例如,要计算5的阶乘,只需调用factorial<5>()
。启用优化后,将只生成120
。不幸的是,这在动态变量中是不可能的。
相关文章:
- 在 C++ 中的数组上使用阶乘函数
- 阶乘问题在 c++ 中给出错误的输出
- 计算阶乘的 C++17 倍表达式中的错误
- 为什么 Lisp 中 1000 阶乘的计算如此之快(并显示正确的结果)?
- 计算最大数字的阶乘
- 高效计算阶乘
- 3 函数加主函数 C 程序计算和显示阶乘
- 当n变大时,在计算阶乘(N)mod m上遇到困难
- 为什么低效的阶乘计算…高效(快速)
- 在编译时计算小整数的阶乘
- 使用指针数组存储阶乘计算的所有中间结果
- 如何在c++中计算阶乘
- 我怎样才能在c++中计算二重的阶乘
- c++模板阶乘计算
- 使用霍纳规则计算 Erf 函数(不使用阶乘和幂)
- 使用迭代和递归计算阶乘时的不同答案
- 阶乘在main中显示错误的答案.在函数中正确计算
- 是否有可能在编译时计算数字的阶乘,但不使用枚举?
- 使用基本数据类型在c++中计算这个阶乘项
- 当我计算一个大的阶乘时,为什么我会得到一个负数