1 条题解
-
0
练24.2 for循环求和
解题思路
使用 for 循环从 1 加到 n,累加器从 0 开始。
正确性说明
处理到 i 时保存前 i 个正整数之和,最终就是目标和。
易错点
按题目要求使用 for,不直接套公式。
复杂度
时间 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; int sum = 0; for (int i = 1; i <= n; i++) sum += i; cout << sum << "\n"; return 0; }
- 1