#include<iostream>
using namespace std;
//求N的阶乘 如fac1(5) 5x4x3x2x1
int fac1(int n)
{
if (n < 0) {
return 0;
}
if (n == 1 || n == 0) {
return 1;
}
return n * fac1(n - 1);
}
//求N的阶乘 如fac1(5) 5x4x3x2x1
int fac2(int n)
{
if (n < 0) {
return 0;
}
if (n == 1 || n == 0) {
return 1;
}
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// N项阶乘的和,如sumFac(5) 5x4x3x2x1 + 4x3x2x1 + 3x2x1 + 2x1 + 1 + 1
int sumFac(int n)
{
if (n < 0) {
return 0;
}
if (n == 0) {
return 1;
}
int result = 1;
int total = 1;
for (int i = 1; i <= n; i++) {
result *= i;
total += result;
}
return total;
}
int main(int argc, const char * argv[])
{
int fac1Value = fac1(5);
int fac2Value = fac2(7);
int sum = sumFac(20);
cout << "5的阶乘 = " << fac1Value << "\n";
cout << "7项阶乘 = " << fac2Value << "\n";
cout << "10项阶乘的和 = " << sum << endl;
return 0;
}
求N的阶乘以及N的阶乘的和
最新推荐文章于 2024-03-22 18:44:17 发布
本文介绍了使用C++实现阶乘的两种方法:递归和循环,并提供了一个额外的函数来计算阶乘序列之和。通过具体示例展示了如何调用这些函数并输出结果。

1040

被折叠的 条评论
为什么被折叠?



