# 基本語法 作者:royyaha ---- 基本架構 ``` cpp #include <iostream> using namespace std; int main() { // code return 0; } ``` ##### 循序執行: 將程式碼放入{ }中,就會由上到下執行。 ---- 變數宣告 ``` cpp int a; long long b, c, d; double d; string s; char ch; ``` ---- ![](https://i.imgur.com/2oVbNXB.png) int範圍$-2 \times 10^9$ ~ $2 \times 10^9$ long long範圍$-9 \times 10^{18}$ ~ $9 \times 10^{18}$ ---- 輸入輸出 ``` cpp int a; string s; cin >> a >> s; cout << a << ' ' << s << endl; ``` ---- 運算子 ``` cpp cout << 2 + ( 3 * 4) / 5 << endl; cout << 10 % 3 << endl; // 取餘數 ``` ##### 等號(=)是指派的意思,跟數學上的等號意義不同 ``` cpp int a = 10; cout << a << endl; a = a + 1; cout << a << endl; ``` ---- 條件判斷 ``` cpp if(42 % 2 == 1) { cout << "42 is odd\n"; } else if(41 % 3 == 0) { cout << "42 is divid by 6\n"; } else { cout << "what the fk is this number\n"; } ``` ---- for-loop ``` cpp for(int i = 0; i < n; i++) { cout << i << ' '; } ``` while-loop ``` cpp int t; while(t--) { cout << t << ' '; } ``` ---- 函數 ``` cpp string addskrskr(string name) { return name + "skrskr"; } void printskrskr(string name) { cout << name << " skrskr\n"; return; // don't return value } ``` ---- 陣列 ``` cpp int a[505] = {10, 20, 30}; // 沒初始到的會補零 ``` --- 競賽常用語法 (今天先跳過) ---- #define ``` cpp #define for0(i, n) for(int i = 0; i < n; i++) #define endl '\n' for0(i, 10) { // 相當於 for(int i = 0; i < 10; i++) cout << i << ' '; } ``` ---- 輸入優化 ``` cpp int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); } ``` --- codeforces介紹 ![](https://i.imgur.com/KUYyC6V.png) ---- --- 參考資料 [C++與演算法](https://www.csie.ntu.edu.tw/~b98902112/cpp_and_algo/index.html)
{"metaMigratedAt":"2023-06-15T13:09:49.969Z","metaMigratedFrom":"Content","title":"基本語法","breaks":true,"contributors":"[{\"id\":\"ac35cf4a-ca96-45e9-a535-ffc508aa0695\",\"add\":1664,\"del\":0}]"}
    362 views