1 条题解
-
0
【例28.2】 求出e的值
解题思路
初始 sum=1 对应 1/0!,term=1。每到第 i 项让 term/=i,就得到 1/i!,再加入 sum,直到 n。
正确性说明
按上述推导执行:每次仅处理当前输入或当前步骤,并把它对答案的贡献计入对应状态。所有需要处理的情况均被覆盖,结束时保存的量就是题目所求。
易错点
题目要求给定截断项数,不能自行多算到收敛;十位小数。
复杂度
时间 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 sum = 1, term = 1; for (int i = 1; i <= n; i++) { term /= i; sum += term; } cout << fixed << setprecision(10) << sum << "\n"; return 0; }
- 1