我比較喜歡解法二的for
解法1:while迴圈
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N = 1e3+10,inf = 0x3f3f3f3f; int main() { int n,ans = 0; cin >> n; ans = n; while(n--) { ans+=n; } cout << ans; return 0; }
解法二:for迴圈
#include<bits/stdc++.h> #define f(i,s,e) for(int i = s; i <= e; i++) #define ll long long using namespace std; const int N = 1e3+10,inf = 0x3f3f3f3f; int main() { int n, sum = 0; cin >> n; for(int i = 1; i <= n; i++) //迴圈1到n { sum += i; //sum累加上迴圈變數i } cout << sum; return 0; }