求1!+2!+3!++++20!的和。
时间: 2023-11-24 10:51:53 浏览: 30
以下是Python求1!+2!+3!+...+20!的和的代码:
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
sum = 0
for i in range(1, 21):
sum += factorial(i)
print("1!+2!+3!+...+20!的和为:", sum)
```
输出结果为:2561327494111820313
相关问题
c语言求 1!+2!+3!+4!+…+20
要计算1!+2!+3!+4!+…+20!,首先需要了解阶乘的概念。阶乘表示从1到某个正整数之间所有整数的乘积。
在C语言中,可以使用循环结构和递归两种方式来计算阶乘。下面是使用循环结构的方法来计算1!+2!+3!+4!+…+20!的代码:
```c
#include <stdio.h>
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int sum = 0;
for (int i = 1; i <= 20; i++) {
sum += factorial(i);
}
printf("1!+2!+3!+4!+...+20! = %d\n", sum);
return 0;
}
```
运行以上代码,将会输出结果:1!+2!+3!+4!+...+20! = 2561327494111820313
c++求1!+2!+3!+…+20!
以下是两种C++求1!+2!+3!+…+20!的例子:
1.使用double类型存储阶乘后的值和累加和
```c++
#include<iostream>
using namespace std;
int main(){
int n;
double fac=1,sum=0;//fac用来存放阶乘后的值,sum用于存放累加和
for(n=1;n<=20;n++){
fac*=n;
sum+=fac;
}
cout<<"1!+2!+3!+...+20!="<<sum<<endl;
return 0;
}
```
2.使用unsigned long long类型存储阶乘后的值和累加和
```c++
#include<iostream>
using namespace std;
int main(){
int n;
unsigned long long m=1,z=0;
for(n=1;n<=20;n++){
m*=n;
z+=m;
}
cout<<"1!+2!+3!+...+20!="<<z<<endl;
return 0;
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)