做题时只提交核心函数的代码即可
// 核心函数
int Factorial(const int N) // 函数定义
{
if (N < 0) // 判断输入是否合法
{
return 0;
}
int factor = 1; // 变量声明并初始化,保持初始化的习惯
for (int idx = 2; idx <= N; ++idx) // 循环计算
{
factor *= idx; // 累乘,等价于 factor = factor * idx;
}
return factor; // 返回结果
}
本题要求实现一个计算非负整数阶乘的简单函数。
函数接口定义:
int Factorial( const int N );
其中N
是用户传入的参数,其值不超过12
。如果N
是非负整数,则该函数必须返回N
的阶乘,否则返回0
。
完整的可执行代码(可以直接在本地编译并运行):
#include <stdio.h> // 编译预处理指令
int Factorial(const int N); // 函数原型声明
int main(void) // 函数头
{
int N = 0; // 变量声明并初始化,保持初始化的习惯
int NF = 0; // 同上
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;
}
int factor = 1; // 变量声明并初始化,保持初始化的习惯
for (int idx = 2; idx <= N; ++idx) // 循环计算
{
factor *= idx; // 累乘,等价于 factor = factor * idx;
}
return factor; // 返回结果
}
输入样例:
5
输出样例:
5! = 120