MOONOJ1052 求阶乘 题解 循环入门题

【题目描述】
输入一个数 n ,你需要输出 n! 。
这里 n! 用于表示 n 的阶乘,即: n! = n * (n-1) * ... * 1 。
比如,5! = 5 * 4 * 3 * 2 * 1 = 120。
【输入格式】
输入只有一个整数n(1<=n<=10)。
【输出格式】
输出"吓得我抱起了抱着(n次)我的小鲤鱼的我(n次)"。结果占一行。
【样例输入】
5
【样例输出】
120
【样例解释】
这里我们输入了5,那么我们的输出就是5!,即120。
【数据规模】
50% 的数据,满足 1≤n≤5;
100%的数据,满足 1≤n≤10。
【题目分析】
这道题也是一道循环的入门题,我们只需要设置一个变量n,初始时n==1,然后开一个for循环,一次让n乘上2,3,...,n就能得到最终的结果了。
我们可以用递推的方式来写。
#include <bits/stdc++.h>
using namespace std;
int n, ans = 1;
int main() {
    cin >> n;
    for (int i = 1; i <= n; i ++) ans *= i;
    cout << ans << endl;
    return 0;
}
也可以用递归的方式来完成。这里我们func(int x) 用于返回x!:
#include <bits/stdc++.h>
using namespace std;
int n, ans = 1;

int func(int x) {
    if (x == 1) return 1;
    return x * func(x-1);
}

int main() {
    cin >> n;
    cout << func(n) << endl;
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/mooncode/p/MOONOJ1052.html