计算序列1+1/2+1/4+1/8…的前N项和
时间: 2023-12-01 08:02:41 浏览: 265
以下是两种计算序列1+1/2+1/4+1/8…的前N项和的方法:
方法一:Python实现
```python
n = int(input())
sum = 0
for i in range(0, n):
a = 2 ** i
sum = sum + 1 / a
print("sum={:.6f}".format(sum))
```
方法二:C语言实现
```c
#include <stdio.h>
int main() {
int N, i;
double sum = 0.0; //定义sum变量获取和
int den = 1; //分母的值
scanf("%d", &N); //获得前N项
for (i = 1; i <= N; i++) {
sum = sum + 1.0 / den; //第一次循环进来sum=0.0+1.0,注意是1.0,否则得不到精度值
den = den * 2; //分母一次循环乘2
}
printf("sum = %.6lf", sum); //打印
return 0;
}
```
阅读全文