编写函数实现输入整数N,计算前N项和S=1+1/2+2/3+3/5+5/8+7/13+9/21.....
时间: 2023-04-08 10:04:47 浏览: 157
好的,这个问题可以回答。以下是实现该功能的 Python 代码:
```python
def calculate_sum(n):
numerator = 1
denominator = 2
sum = 0
for i in range(n):
sum += numerator / denominator
numerator, denominator = denominator, numerator + denominator
return sum
n = int(input("请输入整数N:"))
print("前N项和为:", calculate_sum(n))
```
希望能够帮到你!
相关问题
用c语言编写函数实现输入整数N,计算前N项和S=1+1/2+2/3+3/5+5/8+7/13+9/21.....
好的,这个问题可以回答。以下是用C语言编写的函数实现输入整数N,计算前N项和S=1 1/2 2/3 3/5 5/8 7/13 9/21.....的代码:
```c
#include <stdio.h>
double sum(int n) {
double s = 0, a = 1, b = 2;
int i;
for (i = 1; i <= n; i++) {
s += a / b;
double t = a + b;
a = b;
b = t;
}
return s;
}
int main() {
int n;
printf("请输入整数N:");
scanf("%d", &n);
printf("前%d项和为:%lf\n", n, sum(n));
return 0;
}
```
希望能够帮到你!
阅读全文