PTA 6-8 简单阶乘计算 (10 分)

本题要求实现一个计算非负整数阶乘的简单函数

函数接口定义:

int Factorial( const int N );

其中N是用户传入的参数,其值不超过12。如果N是非负整数,则该函数必须返回N的阶乘,否则返回0

裁判测试程序样例:

#include 

int Factorial( const int N );

int main()
{
    int N, NF;

    scanf("%d", &N);
    NF = Factorial(N);
    if (NF)  printf("%d! = %d\n", N, NF);
    else printf("Invalid input\n");

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

5
// 结尾无空行

输出样例:

5! = 120
// 结尾无空行

做法一

使用递归来做,需要考虑 N < 0N = 0 的情况

int Factorial( const int N ) {

    if (N < 0) {
        return 0;
    }

    if (N == 0) {
        return 1;
    } else {
        return Factorial(N - 1) * N;
    }


}

做法二

使用 while 循环来做,因为题目要求的形参是 const int N,不能够修改,所以使用 int n = N; 之后可以用 n--;

int Factorial( const int N ) {

    int sum = 1;
    int n = N;

    if (n < 0) {
        return 0;
    }

    while(n) {
        sum *= n;
        n--;
    }

    return sum;

}

做法三

int Factorial( const int N ) {

    int sum = 1;
    int n = N;

    if (n < 0) {
        return 0;
    }

    for (int i = n; i > 0; i--) {

        sum *= i;

    }

    return sum;

}

做法四

int Factorial( const int N ) {

    int sum = 1;

    if (N < 0) {
        return 0;
    }

    for (int i = 1; i <= N; i++) {

        sum *= i;

    }

    return sum;

}

你可能感兴趣的:(C,java,开发语言,后端)