编写程序求1!+2!+3!+..+10!
时间: 2024-01-02 17:21:32 浏览: 77
以下是两种C语言编写程序求1!+2!+3!+..+10!的例子:
引用:
```c
#include <stdio.h>
int main() {
int i = 0;
int result = 1;
int sum = 0;
for (i = 1; i < 11; i++) {
result *= i; // result会保留上一个的阶乘进行相乘
sum += result;
}
printf("1!+2!+3!+……+10!:%d", sum);
return 0;
}
```
引用:
```c
#include <stdio.h>
int main() {
int i = 0;
int j = 0;
int n = 0;
int sum = 0;
int result = 1;
for ( i = 1; i < 11; i++) {
result = 1; // 计算下一个阶乘时,要将result初始化
for (j = 1; j <= i; j++) {
result *= j;
}
sum += result;
}
printf("1!+2!+3!+……+10!:%d", sum);
return 0;
}
```
相关问题
编写程序求1! +2! +3! ..+10!
以下是C语言和Python两种编写程序求1! +2! +3! ..+10!的例子:
1.C语言程序
```c
#include <stdio.h>
int main()
{
int i, j;
double e = 1, factorial = 1;
for (i = 1; factorial >= 0.000001; i++)
{
factorial = 1;
for (j = 1; j <= i; j++)
{
factorial *= j;
}
e += 1.0 / factorial;
}
printf("e = %lf\n", e);
return 0;
}
```
2.Python程序
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
sum = 0
for i in range(1, 11):
sum += factorial(i)
print(sum) # 输出:4037913
```
编写程序,求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!的正确性。
阅读全文