编写程序,求sum=1+1\2!+1\3!+......+1\20!
时间: 2023-10-05 21:11:49 浏览: 70
```
#include <iostream>
using namespace std;
int main() {
double sum = 0.0, factorial = 1.0; // sum表示累加和,factorial表示阶乘
for (int i = 1; i <= 20; i++) {
factorial *= i; // 计算i的阶乘
sum += 1 / factorial; // 将1/i!累加到sum中
}
cout << "sum = " << sum << endl;
return 0;
}
```
输出结果为:
```
sum = 1.71828
```
相关问题
编写程序,求1!+2!+3!+...+10!,验证1!+...+10!
以下是Python程序,用于计算1!+2!+3!+...+10!和1!+...+10!的结果:
```python
# 计算1!+2!+3!+...+10!
sum1 = 0
factorial = 1
for i in range(1, 11):
factorial *= i
sum1 += factorial
print("1!+2!+3!+...+10! =", sum1)
# 计算1!+...+10!
sum2 = 0
for i in range(1, 11):
factorial = 1
for j in range(1, i+1):
factorial *= j
sum2 += factorial
print("1!+...+10! =", sum2)
```
输出结果为:
```
1!+2!+3!+...+10! = 4037913
1!+...+10! = 4037913
```
可以看到,两个结果相等,因此验证了1!+...+10!的正确性。
编写程序,求1!+2!+3!+...+10!,验证1!+...+10!用c语言
以下是用C语言编写程序,求1!+2!+3!+...+10!的代码:
```c
#include <stdio.h>
int main() {
int n = 10;
int sum = 0;
int sum1 = 1;
for(int i = 1; i <= n; i++) {
sum1 *= i;
sum += sum1;
}
printf("%d\n", sum);
return 0;
}
```
运行结果为:4037913
阅读全文