文章目录
题目
要求实现一个计算非负整数阶乘的简单函数。
函数接口定义
int Factorial( const int N );
其中N是用户传入的参数,其值不超过 12 12 。如果 N N 是非负整数,则该函数必须返回 N N 的阶乘,否则返回 0 0 。
裁判测试程序样例
#include <stdio.h> 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
题解
解题思路
首先判断传入函数的数字,如果小于
0 0 直接返回
0 0 ;如果是
0 0 或
1 1 直接返回
1 1 ;如果是大于
1 1 的数字则利用
f o r for 循环,从
1 1 开始相乘,因为输入的至小于
12 12 ,因此可以用
i n t int 类型,最后返回和即可。
注:
0 0 的阶乘为
1 1 ;
完整代码
#include <stdio.h> 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; } /* 你的代码将被嵌在这里 */ int Factorial(const int N) { if (N < 0) { return 0; } else { if (N <= 1) { return 1; } else { int i = 1, sum = 1; for (i; i <= N; i++) { sum *= i; } return sum; } } }
AC代码
int Factorial(const int N) { if (N < 0) return 0; else { if (N <= 1) return 1; else { int i = 1, sum = 1; for (i; i <= N; i++) sum *= i; return sum; } } }