编写程序,求出1+(1+2)+(1+2+3)+…+(1+2+3+4+…n)的和,函数以n为参数,n用input从键盘输入,最后以打印的方式输出结果,python代码输出
时间: 2023-09-28 07:03:20 浏览: 70
以下是Python代码实现:
```python
n = int(input("请输入一个正整数n:"))
result = 0
for i in range(1, n+1):
temp = 1
for j in range(1, i+1):
temp *= j
result += temp
print("1 (1 2) (1 2 3) … (1 2 3 4 …n)的和为:", result)
```
输出结果类似于:
```
请输入一个正整数n:5
1 (1 2) (1 2 3) … (1 2 3 4 …n)的和为: 153
```
相关问题
编写程序求1!+2!+3!+ …+n!
以下是使用Java编写程序求1!+2!+3!+ …+n!的例子:
```java
import java.util.Scanner;
public class FactorialSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数n:");
int n = scanner.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
System.out.println("1!+2!+3!+...+n!的和为:" + sum);
}
public static int factorial(int num) {
int result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}
}
```
编写程序求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
```
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)