6-8 简单阶乘计算 (10 分)
1. 题目摘自
https://pintia.cn/problem-sets/14/problems/740
2. 题目内容
本题要求实现一个计算非负整数阶乘的简单函数。
函数接口定义:
int Factorial( const int N );
其中N是用户传入的参数,其值不超过12。如果N是非负整数,则该函数必须返回N的阶乘,否则返回0。
输入样例:
5
输出样例:
5! = 120
3. 源码参考
#include <iostream>
using namespace std;
int Factorial( const int N );
int main()
{
int N, NF;
cin >> N;
NF = Factorial(N);
if (NF)
{
cout << N << "! = " << NF << endl;
}
else
{
cout << "Invalid input" << endl;
}
return 0;
}
int Factorial( const int N )
{
int n = N;
int s = 1;
while(n)
{
s *= n;
n--;
}
return s;
}
网友评论