求 1!+2!+3!+……+7! 的值
时间: 2023-11-16 22:06:44 浏览: 52
题目要求的是1!+2!+3!+……+7!的值,其中“!”表示阶乘。可以使用递归函数来实现这个求和过程。具体实现方法如下:
```c++
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int sum = 0;
for (int i = 1; i <= 7; i++) {
sum += factorial(i);
}
cout << "1!+2!+3!+...+7!=" << sum << endl;
return 0;
}
```
运行结果为:1!+2!+3!+...+7!=5913
相关问题
while循环求1!+3!+……+(2n+1)!
以下是使用while循环求1!+3!+……+(2n+1)!的Python代码:
```python
n = int(input("请输入n的值:"))
result = 0
i = 1
while i <= 2*n+1:
factorial = 1
j = 1
while j <= i:
factorial *= j
j += 1
result += factorial
i += 2
print("1!+3!+……+(2n+1)!的结果为:", result)
```
代码说明:
1. 首先通过input函数获取用户输入的n的值。
2. 定义result变量用于存储最终结果,初始化为0。
3. 定义i变量用于循环计算每一项的阶乘,初始化为1。
4. 外层while循环控制计算的项数,循环条件为i <= 2*n+1。
5. 在内层while循环中计算i的阶乘,循环条件为j <= i,每次循环j自增1,factorial变量用于存储阶乘的结果,初始化为1,每次循环将j乘到factorial中。
6. 计算完当前项的阶乘后,将其加到result中。
7. 每次循环i自增2,以便计算下一项。
8. 循环结束后,输出最终结果。
用c++输出1!+2!+3!+……+20!的值
以下是将1!到20!的值输出到屏幕的C代码:
```c
#include <stdio.h>
int main() {
int i;
long long factorial = 1;
for(i=1; i<=20; i++) {
factorial *= i;
printf("%d! = %lld\n", i, factorial);
}
return 0;
}
```
输出:
```
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
```