5.+编程实现:求序列2/1+3/2+5/3+8/5+…前20项之和
时间: 2023-12-12 10:32:32 浏览: 72
是两种编程语言实现序列2/1+3/2+5/3+8/5+…前20项之和的代码:
C语言实现:
```c
#include <stdio.h>
int main() {
float top = 2, base = 1;
float t, sum = 0;
int times = 0;
while (times++ < 20) {
sum += top / base;
t = base;
base = top;
top += t;
}
printf("前20项和为:%f\n", sum);
return 0;
}
```
Java语言实现:
```java
public class Main {
public static void main(String[] args) {
double a = 2.0;
double b = 1.0;
double num;
double sum = 0.0;
for (int i = 1; i <= 20; i++) {
num = a / b;
sum += num;
a = a + b;
b = a - b;
}
System.out.println("前20项和为:" + sum);
}
}
```
阅读全文