如何在c++中计算阶乘

How to calculate factorial in c++

本文关键字:计算 阶乘 c++      更新时间:2023-10-16

通过函数计算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。不幸的是,这在动态变量中是不可能的。