PTA:7-84 求分数序列前N项和 (15分)

7-84 求分数序列前N项和 (15分)

本题要求编写程序,计算序列 2/1+3/2+5/3+8/5+… 的前N项之和。注意该序列从第2项起,每一项的分子是前一项分子与分母的和,分母是前一项的分子。

输入格式:
输入在一行中给出一个正整数N。

输出格式:
在一行中输出部分和的值,精确到小数点后两位。题目保证计算结果不超过双精度范围。

输入样例:
20

输出样例:
32.66

思路
按照题目给的规律,不停的变换分子分母即可。

#include <bits/stdc++.h>
using namespace std;

int main(){
	int n,cnt=0;
	double sum=0,a=1,b=1;
	cin >> n;
	while(cnt<n){
		double temp = b;
		b = a;	
		a = a + temp;
		sum += a/b;
		cnt++;
	}
	cout << fixed << setprecision(2) << sum;  //保留两位小数 
	return 0;
}

欢迎大家批评改正!!!

发布了39 篇原创文章 · 获赞 2 · 访问量 3423

猜你喜欢

转载自blog.csdn.net/weixin_43581819/article/details/104010193