有一分数序列: 2/3,3/5,5/7,8/9,13/11,21/13,...,求出这个数列的前n项
时间: 2024-09-30 21:09:28 浏览: 34
python 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和 (示例)
5星 · 资源好评率100%
这是一个类似于斐波那契数列的数列,但分子和分母的规律不同。分子的规律是从第三项开始,每项都是前两项分子之和,分母的规律是从第二项开始,每项都是前一项分母与前一项分子之和。以下是几种不同语言的解法:
Python3代码:
```
def f(n):
a, b = 2, 3
total = a / b
for i in range(n - 1):
a, b = b, a + b - 1
total += a / b
print("前", n, "项和为:", total)
f(20)
```
Java代码:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt(); float a = 2f, b = 3f, c, d = 3f, h = 0f;
for (int i = 1; i <= n; i++) {
h += a / d;
c = a + b;
a = b;
b = c;
d = b - a;
}
System.out.printf("前%d项和为:%.2f\n", n, h);
}
}
```
C++代码:
```
#include <iostream>
using namespace std;
int main() {
int n;
float a = 2, b = 3, c, d = 3, h = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
h += a / d;
c = a + b;
a = b;
b = c;
d = b - a;
}
printf("前%d项和为:%.2f", n, h);
return 0;
}
```
--相关问题--:
阅读全文