目录
这次呢,我给大家讲讲怎么用 C++ 实现输入一个数,输出它的阶乘
阶乘的定义
n! = n * (n - 1) * (n - 2) * (n - 3) * …… * 2 * 1
第一种实现方法
我们的第一种实现方法呢,是用循环,枚举从 n 到 1 的所有数,然后乘起来,正确性毋庸置疑。代码如下:
#include <iostream>
using namespace std;
typedef long long ll;
ll n;
ll factorial(ll x) {
ll s = 1;
while(x)
s *= x--;
return s;
}
int main() {
cin >> n;
cout << factorial(n) << endl;
return 0;
}
运行结果:
第二种实现方法
第二种呢,就是用递归啦,每次 factorial(x) = x * factorial(x - 1),当然,要有递归边界,如果 x 等于 1 时,返回 1,代码如下:
#include <iostream>
using namespace std;
typedef long long ll;
ll n;
ll factorial(ll x) {
return x == 1 ? 1 : x * factorial(x - 1);
}
int main() {
cin >> n;
cout << factorial(n) << endl;
return 0;
}
这里用到了三目运算符,转换成 if 语句是:
if(x == 1)
return 1;
else
return x * factorial(x - 1);
运行结果是一样的:
尾声
以上就是阶乘的两种实现方法,如果对各位有帮助的话,就请各位帮忙点个赞,加个关注!!!
最后,祝愿大家在 OI 的路上一路顺风!