当然也可以用迭代(就是循环)来求阶乘,递归适用于选择结构,迭代适用于循环结构。
能用递归解决的问题,一定能用迭代来解决。
/*
C++利用递归求一个数的阶乘
递归:即自己调用自己
分类:分为直接调用和间接调用
直接调用:不通过其他函数直接在本函数内,调用自己。
间接调用:通过多步操作,在其他函数内调用本身。
*/
#include <iostream>
using namespace std;
int factorial(int n)
{
//方法一
//if (n == 0)
//{
// return 1;
//}
//else
//{
// return n * factorial(n - 1);
//}
//方法二
return (n == 0) ? 1 : (n * factorial(n - 1));
}
void main()
{
int n;
int res;
cout << "求一个正整数的阶乘:" << "\n" << endl;
cout << "请输入一个正整数:";
cin >> n;
cout << endl;
res = factorial(n);
cout << n << "的阶乘为:" << res << endl;
cout << endl;
system("pause");
}