2.c++写 计算s = 1!+2!+3!+…+n!的源程序,书写阶乘函数,并调用求上面式子
时间: 2023-11-27 21:48:19 浏览: 34
以下是C++计算s = 1!+2!+3!+…+n!的源程序,包括阶乘函数的书写和调用:
```c++
#include <iostream>
using namespace std;
int factorial(int n) { // 阶乘函数
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n, s = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
s += factorial(i); // 累加每个数的阶乘
}
cout << s << endl;
return 0;
}
```
相关问题
用C++计算s = 1!+2!+3!+…+n!的源程序,书写阶乘函数,并调用上面式子
以下是用C++计算s = 1!+2!+3!+…+n!的源程序:
```cpp
#include <iostream>
using namespace std;
int factorial(int n) {
int f = 1;
if (n < 0) {
cout << "你输入的数据有误!" << endl;
} else {
for (int i = 1; i <= n; i++) {
f *= i;
}
}
return f;
}
int main() {
int n, s = 0;
cout << "输入一个数:" << endl;
cin >> n;
for (int i = 1; i <= n; i++) {
s += factorial(i);
}
cout << "s = " << s << endl;
return 0;
}
```
c语言用函数定义和调用计算s = 1!+2!+3!+…+n!的源程序,书写阶乘函数
以下是C语言用函数定义和调用计算s = 1!+2!+3!+…+n!的源程序,以及阶乘函数的代码:
```c
#include <stdio.h>
// 阶乘函数
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
// 计算1!+2!+3!+...+n!的函数
int sumOfFactorials(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i); }
return sum;
}
// 主函数
int main() {
int n;
printf("请输入一个正整数n:");
scanf("%d", &n);
printf("1!+2!+3!+...+%d! = %d\n", n, sumOfFactorials(n));
return 0;
}
```
在上面的代码中,`factorial`函数用于计算阶乘,`sumOfFactorials`函数用于计算1!+2!+3!+...+n!,`main`函数用于读取用户输入的n并输出结果。