returns 阶乘 C++ 的递归函数

recursive function that returns factorial C++

我正在尝试解决 C++ Primer Plus 书中的以下练习。

Define a recursive function that takes an integer argument and returns the factorial of that argument. Recall that 3 factorial, written 3!, equals 3 × 2!, and so on, with 0! defined as 1. In general, if n is greater than zero, n! = n * (n - 1)!. Test your function in a program that uses a loop to allow the user to enter various values for which the program reports the factorial.

我编写了进入 main() 的代码。

#include <iostream>
using namespace std;

int factorial(int n);


int main()
{
    int number= 0;
    cout<<"Enter a number(0 to quit): ";
    while (cin >> number && number! = 0)
    {
        cout<< "Here is the factorial of the number: "<< factorial (number) << ". \n"
        "Enter next number(0 to quit): ";
    }


    return 0;
}

现在我想不出合适的递归函数声明。有人可以通过编写最简单的(对于编程新手)来帮助掌握此练习的函数声明吗?

我会按照以下方式做一些事情:

int factorial(int n){
  if(n<=0)
    return 1;
  int num=factorial(n-1);
  if(num)
    return n*num;
  return 0;
}

在设计计算任何数的阶乘的递归算法时,我们必须首先确定基本情况,这是我们可以不用递归解决的计算部分。即 n = 0 然后 factorial(n) = 1.

的情况

这里讲的是当n等于0的时候怎么解,但是当n大于0的时候怎么办呢?也就是递归的情况,或者说是我们用递归来解决的那部分问题。 If n > 0, then factorial(n) = n * factorial(n-1)。这表明如果 n 大于 0,则 n 的阶乘是 n-1.

的阶乘 n 倍
int factorial(int n)
{
    if (n == 0)
        return 1; // base case
    else
        return n * factorial(n-1); // recursive case
}

您可以使用如下非常短的函数,但它与@superPhreshHackerKid 提供的答案相同

int factorial(int n){
    if (n > 0)
        return n * factorial(n-1);
    return 1;
}

希望对您有所帮助