1 条题解
-
0
【例37.2】 求分数序列和
解题思路
分子q初始2、分母p初始1。每轮先累加q/p,再将下一组更新为(q+p,q),注意同时更新不能丢失旧q。
正确性说明
计算规则直接来自题目定义。按所述顺序处理时,已完成部分的结果被准确保存在累加量、计数或当前状态中;下一步只加入新增贡献。最终得到完整要求的结果。
易错点
先用临时变量保存下一分子,再更新分母;四位小数。
复杂度
时间 O(n),额外空间 O(1)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; double q = 2, p = 1, sum = 0; for (int i = 0; i < n; i++) { sum += q / p; double next = q + p; p = q; q = next; } cout << fixed << setprecision(4) << sum << "\n"; return 0; }
- 1