请用c++编程:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13... 求出这个数列的前n 项之和。保留小数点后10位。 输入样例: 5 输出样例: 8.3916666667 数据规模 1<= n <=40
时间: 2023-12-13 08:53:54 浏览: 32
以下是用递推的方法实现的代码:
```cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int n;
cin >> n;
double a = 2, b = 1, sum = 0;
for (int i = 1; i <= n; i++) {
sum += a / b;
double t = a + b;
b = a;
a = t;
}
cout << fixed << setprecision(10) << sum << endl;
return 0;
}
```
首先读入输入的数 $n$,然后定义三个变量 $a$、$b$ 和 $sum$,分别表示数列中当前项的分子、分母和前 $n$ 项之和。初始时,$a$ 和 $b$ 分别赋值为 $2$ 和 $1$,$sum$ 赋值为 $0$。
接下来使用一个循环,从 $1$ 到 $n$ 遍历数列中的每一项,每次将 $a / b$ 加到 $sum$ 中,然后计算出数列中下一项的分子和分母,分别赋值给 $a$ 和 $b$。
最后输出 $sum$,并且使用 `fixed` 和 `setprecision` 控制输出的小数位数为 $10$。
相关问题
用c++写以下程序:有一分数序列: 2/1 3/2 5/3 8/5 13/8 21/13...... 求出这个数列的前N项之和
以下是用C语言实现这个程序的代码:
#include <stdio.h>
int main() {
int i, n, t1 = 2, t2 = 1, nextTerm;
float sum = 0;
printf("输入要计算的数列项数: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i) {
sum += (float)t1 / t2;
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
printf("前%d项之和为%.2f\n", n, sum);
return 0;
}
如果您有更多的问题,请随时问我。
有一分数序列:2/1 3/2 5/3 8/5 13/821/13......求出这个数列的前N项之和,保留两位小数。使用c++
是使用C++计算该分数序列前N项之和的代码,保留两位小数:
```c++
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int n = 20; // 前N项
double a = 2, b = 1, sum = 0, temp;
for (int i = 1; i <= n; i++) {
sum += a / b;
temp = a + b;
b = a;
a = temp;
}
cout << fixed << setprecision(2) << sum << endl;
return 0;
}
```
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)