n! = 1 X 2 X 3 X … X n; 如果 n>0
n =1; 如果 n = 0
factorial(n) = n X fafactorial(n-1); 如果 n> 0
factorial(n) = 1; 如果 n = 0
int factorial(int num)
{
if (num == 0) //基本情况返回1;
return 1;
else
return num * factorial(num - 1);
}
来看一个显示 3! 的值的程序,其语句如下:cout << factorial(3) << endl;
第一次调用该函数时,num 被设置为 3,所以 if 语句将执行以下代码行:return num * factorial(num - 1);
虽然这是一个 return 语句,但它并不会立即返回,这是因为在确定返回值之前,必须确定 factorial(num-1) 的值。该函数被递归调用,直到第 4 次调用,其中的 num 参数将被设置为 0。图 1 中直观地说明了函数每次调用期间 num 的值和返回值。
// This program demonstrates a recursive function
// to calculate the factorial of a number.
#include <iostream>
using namespace std;
// Function prototype
int factorial(int);
int main()
{
int number;
cout << "Enter an integer value and I will display\n";
cout << "its factorial: ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial (number) << endl;
return 0;
}
int factorial(int num)
{
if (num == 0) //base case
return 1;
else
return num * factorial(num - 1);
}
程序输出结果:
Enter an integer value and I will display
its factorial: 4
The factorial of 4 is 24
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有