典型循环:s=1!+2!+3!+……+n!,用三种循环编程
时间: 2023-10-01 14:06:48 浏览: 97
java基础编程:求1+2!+3!+...的前n项的和
1. for循环
```
n = int(input("请输入一个正整数:"))
s = 0
for i in range(1, n+1):
fac = 1
for j in range(1, i+1):
fac *= j
s += fac
print("s =", s)
```
2. while循环
```
n = int(input("请输入一个正整数:"))
s = 0
i = 1
while i <= n:
fac = 1
j = 1
while j <= i:
fac *= j
j += 1
s += fac
i += 1
print("s =", s)
```
3. do-while循环
```
n = int(input("请输入一个正整数:"))
s = 0
i = 1
while True:
fac = 1
j = 1
while j <= i:
fac *= j
j += 1
s += fac
i += 1
if i > n:
break
print("s =", s)
```
阅读全文