目录
题目:
本题要求实现一个计算非负整数阶乘的简单函数。
函数接口定义:
int Factorial( const int N );
其中N
是用户传入的参数,其值不超过12。如果N
是非负整数,则该函数必须返回N
的阶乘,否则返回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
结尾无空行
分析:
就是算阶乘啦,除了一般的方法外还可以尝试使用递归
答案①:
int Factorial(const int N) {
int s = 0;
if (N >= 0) {
s = 1;
for (int i = 0; i < N; i++) {
s *= i + 1;
}
}
return s;
}
答案②:
int Factorial(const int N) {
int s = 0;
if (N == 0) {
s = 1;
}
else if (N > 0) {
s = N * Factorial(N - 1);
}
return s;
}