编写程序,在程序中定义一个函数,计算:1+1/2+1/3+.....+1/n。(考虑递归和非递归两种实现方式)
时间: 2023-05-30 11:05:28 浏览: 99
c++求1+1/2+1/3+...+1/n
5星 · 资源好评率100%
非递归实现:
```python
def sum_of_series(n):
result = 0.0
for i in range(1, n+1):
result += 1.0/i
return result
n = int(input("请输入n:"))
print("1/1 + 1/2 + 1/3 + ... + 1/{} = {}".format(n, sum_of_series(n)))
```
递归实现:
```python
def sum_of_series_recursive(n):
if n == 1:
return 1.0
else:
return 1.0/n + sum_of_series_recursive(n-1)
n = int(input("请输入n:"))
print("1/1 + 1/2 + 1/3 + ... + 1/{} = {}".format(n, sum_of_series_recursive(n)))
```
阅读全文