C++

C++ 入門

程式基本概念

編譯與執行

            
            // 編譯
            $ g++ p1.cpp -o p1

            // 執行
            $ ./p1

            // 執行時輸入測資
            $ ./p1 < d1.txt

            // 編譯及執行
            $ g++ p1.cpp -o p1 && ./p1

            // APCS 指令
            $ g++ -g -O2 -std=gnu++11 -static -o p1.out p1.cpp -lm
            $ ./p1.out
            
        

Output(輸出)

第一支程式

            
            #include <iostream>
            using namespace std;

            int main() {
                cout << "Hello, World!" << endl;
                return 0;
            }
            
        

各種進位值

進位制基底與位數範圍
  • 10進位(Dec): 0123456789
  •  2進位(Bin): 01
  •  8進位(Oct): 01234567
  • 16進位(Hex): 0123456789abcdef (a~f 依序表示 10~15)
            
            #include <iostream>
            using namespace std;

            int main() {
                int n = 987;

                cout << "Dec: " << n << endl;
                cout << "Oct: " << oct << n << endl;
                cout << "Hex: " << hex << n << endl;
                cout << showbase;
                cout << "Oct: " << oct << n << endl;
                cout << "Hex: " << hex << n << endl;
                return 0;
            }
            
        

Input(輸入)

名字與年齡

  • string: 字串 (必須用一對雙引號 "" 括住)
  •  int: 整數
  •  cin: 輸入
  • cout: 輸出
  • endl: 換行
            
            #include <iostream>
            #include <string>
            using namespace std;

            int main() {
                string name;
                int age;

                cout << "What is your name? ";
                cin >> name;
                cout << "How old are you? ";
                cin >> age;
                cout << "Name: " << name << endl;
                cout << "Age: " << age << endl;
                return 0;
            }
            
        

兩數相加

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b;

                cout << "a: ";
                cin >> a;
                cout << "b: ";
                cin >> b;
                cout << "Sum: " << a + b << endl;
                return 0;
            }
            
        

Math(計算)

兩數相減

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b;
                int x;

                cout << "a: ";
                cin >> a;
                cout << "b: ";
                cin >> b;
                x = a - b;
                cout << "Difference: " << x << endl;
                return 0;
            }
            
        

三數相乘

一列一數 vs. 一列多數

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b, c;
                int x;

                cin >> a >> b >> c;
                x = a * b * c;
                cout << "Product: " << x << endl;
                return 0;
            }
            
        

和差問題

            
            #include <iostream>
            using namespace std;

            int main() {
                int sum = 10;
                int diff = 4;
                int large, small;

                large = (sum + diff) / 2;
                small = (sum - diff) / 2;
                cout << "Large number: " << large << endl;
                cout << "Small number: " << small << endl;
                return 0;
            }
            
        

常用算術運算

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b;

                cout << "a: ";
                cin >> a;
                cout << "b: ";
                cin >> b;
                // 加法(+)
                cout << a << " + " << b << " = " << a + b << endl;
                // 減法(-)
                cout << a << " - " << b << " = " << a - b << endl;
                // 乘法(*)
                cout << a << " * " << b << " = " << a * b << endl;
                // 除法(/) 其中之一為浮點數,結果為浮點數
                cout << a << " / " << b << " = " << (float)a / b << endl;
                // 商數(/) 兩整數相除結果為商數
                cout << a << " / " << b << " = " << a / b << endl;
                // 餘數(%)
                cout << a << " % " << b << " = " << a % b << endl;
                return 0;
            }
            
        

個位與十位

            
            #include <iostream>
            using namespace std;

            int main() {
                int n;
                cout << "n: ";
                cin >> n;
                cout << "units digit: " << n % 10 << endl;
                cout << " tens digit: " << n / 10 << endl;
                return 0;
            }
            
        

圓周率第一版

            
            #include <iostream>
            #include <iomanip>
            #include <cmath>
            using namespace std;

            int main() {
                double pi = M_PI;
                cout << fixed;
                cout << setprecision(4) << pi << endl;
                cout << setprecision(6) << pi << endl;
                cout << setprecision(8) << pi << endl;
                return 0;
            }
            
        

圓周率第二版

            
            #include <iostream>
            #include <cmath>
            using namespace std;

            int main() {
                double pi = M_PI;
                printf("%f\n", M_PI);
                printf("%.2f\n", M_PI);
                printf("%.4f\n", M_PI);
                printf("%.8f\n", M_PI);
                return 0;
            }
            
        

浮點數精度

            
            #include <iostream>
            #include <iomanip>
            #include <cmath>
            using namespace std;

            int main() {
                double a = 12.40;
                double b = 12.50;
                double c = 12.55;
                double d = 12.60;

                cout << setprecision(32);
                cout << a << endl;
                cout << b << endl;
                cout << c << endl;
                cout << d << endl;
                cout << endl;
                cout << round(a) << endl;
                cout << round(b) << endl;
                cout << round(c) << endl;
                cout << round(d) << endl;
                return 0;
            }
            
        

Variable(變數)

變數最大值

            
            #include <iostream>
            #include <climits>
            #include <cfloat>
            using namespace std;

            int main() {
                char i1 = CHAR_MAX;
                short i2 = SHRT_MAX;
                int i4 = INT_MAX;
                long i8 = LONG_MAX;
                float f4 = FLT_MAX;
                double f8 = DBL_MAX;

                cout << sizeof(i1) << " : " << i1 << endl;
                cout << sizeof(i2) << " : " << i2 << endl;
                cout << sizeof(i4) << " : " << i4 << endl;
                cout << sizeof(i8) << " : " << i8 << endl;
                cout << sizeof(f4) << " : " << f4 << endl;
                cout << sizeof(f8) << " : " << f8 << endl;
                return 0;
            }
            
        

整數範圍

            
            #include <iostream>
            #include <climits>

            int main() {
                printf(" CHAR: %d ~ %d  \n", CHAR_MIN, CHAR_MAX);
                printf(" SHRT: %d ~ %d  \n", SHRT_MIN, SHRT_MAX);
                printf("  INT: %d ~ %d  \n", INT_MIN, INT_MAX);
                printf(" LONG: %ld ~ %ld\n", LONG_MIN, LONG_MAX);
                printf("UCHAR: %d \n", UCHAR_MAX);
                printf("USHRT: %d \n", USHRT_MAX);
                printf(" UINT: %u \n", UINT_MAX);
                printf("ULONG: %lu\n", ULONG_MAX);
                return 0;
            }
            
        
TypeRange
CHAR-128 ~ 127
SHRT-32768 ~ 32767
INT-2147483648 ~ 2147483647
LONG-9223372036854775808 ~ 9223372036854775807
UCHAR255
USHRT65535
UINT4294967295
ULONG18446744073709551615

整數與字元

            
            #include <iostream>
            #include <iomanip>
            using namespace std;

            int main() {
                int i = 65;
                char c = 'A';

                cout << i << endl;
                cout << (int)c << endl;
                cout << (char)i << endl;
                cout << c << endl;
                return 0;
            }
            
        

兩數交換

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b, temp;

                cout << "Enter 2 numbers: ";
                cin >> a >> b;
                temp = a;
                a = b;
                b = temp;
                cout << a << " " << b << endl;
                return 0;
            }
            
        

浮點數轉整數

            
            #include <iostream>
            using namespace std;

            int main() {
                float a, b;
                int n;

                cout << "Enter 2 numbers: ";
                cin >> a >> b;

                cout << a / b << endl;
                n = (int)(a / b);
                cout << n << endl;
                return 0;
            }
            
        

兩數相除

            
            #include <iostream>
            #include <iomanip>
            using namespace std;

            int main() {
                int dividend = 19;
                int divisor1 = 3;
                float divisor2 = 6.0;
                float answer;

                answer = dividend / divisor1;
                cout << "answer1: " << answer << endl;

                cout << fixed << setprecision(3);

                answer = dividend / divisor2;
                cout << "answer2: " << answer << endl;

                answer = (float)dividend / divisor1;
                cout << "answer3: " << answer << endl;

                return 0;
            }
            
        

變數值與位址

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b, c;
                cout << "Enter 3 numbers: ";
                cin >> a >> b >> c;
                cout << a << " " << &a << endl;
                cout << b << " " << &b << endl;
                cout << c << " " << &c << endl;
                return 0;
            }
            
        

Decision making(決策) - 決策式(分支或選擇結構)

if條件式

            
            #include <iostream>
            #include <string>
            using namespace std;

            int main() {
                string weather = "sunny";

                cout << "Let's hang out.\n";
                if (weather == "sunny") {
                    cout << "Sure. Why not?\n";
                }
                return 0;
            }
            
        

if-else條件否則式

            
            #include <iostream>
            #include <string>
            using namespace std;

            int main() {
                string weather = "";

                cout << "Let's hang out.\n";
                cout << "How is the weather? ";
                cin >> weather;

                if (weather == "sunny") {
                    cout << "Sure. Why not?\n";
                }
                else {
                    cout << "I want to stay at home.\n";
                }
                return 0;
            }
            
        

絕對值

            
            #include <iostream>
            using namespace std;

            int main() {
                int n;
                cout << "> ";
                cin >> n;
                cout << "abs: " << abs(n) << endl;
                return 0;
            }
            
        

三數最大值

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b, c;
                int max = 0;
                cout << "Enter 3 numbers: ";
                cin >> a >> b >> c;
                max = a;
                if (max < b) {
                    max = b;
                }
                if (max < c) {
                    max = c;
                }
                cout << max << endl;
                return 0;
            }
            
        

三元運算子

條件式 ? 條件成立的運算式 : 不成立的運算式

            
            #include <iostream>
            using namespace std;

            int main() {
                int a, b, c;
                int max = 0;
                cout << "Enter 3 numbers: ";
                cin >> a >> b >> c;
                max = (a > b) ? a : b;
                max = (max > c) ? max : c;
                cout << max << endl;
                return 0;
            }
            
        

成績平均績點

            
            #include <iostream>
            using namespace std;

            int main() {
                int grade;

                cout << "Your grade: ";
                cin >> grade;

                if (grade>=80) {
                    cout << "A, GPA is 4\n";
                }
                else if (grade<80 && grade>=70) {
                    cout << "B, GPA is 3\n";
                }
                else if (grade<70 && grade>=60) {
                    cout << "C, GPA is 2\n";
                }
                else if (grade<60 && grade>=50) {
                    cout << "D, GPA is 1\n";
                }
                else {
                    cout << "F, GPA is 0\n";
                }
                return 0;
            }
            
        

switch結構

            
            #include <iostream>
            using namespace std;

            int main() {
                int x, y;
                char op;

                cout << "x: ";
                cin >> x;
                cout << "y: ";
                cin >> y;
                cout << "Choose an operation (+ - * / %): ";
                cin >> op;

                switch(op) {
                    case '+': cout << x + y;
                              break;
                    case '-': cout << x - y;
                              break;
                    case '*': cout << x * y;
                              break;
                    case '/': cout << x / y;
                              break;
                    case '%': cout << x % y;
                              break;
                    default: cout << "Wrong operation!";
                }
                printf("\n");
                return 0;
            }
            
        

分階傳訊

            
            #include <iostream>
            #include <string>
            using namespace std;

            int main() {
                string msg;
                int level;

                cout << "Message: ";
                getline(cin, msg);
                cout << "Level (1 to 9): ";
                cin >> level;

                switch(level) {
                    case 1: cout << "Send" << msg << "to level 1" << endl;
                    case 2: cout << "Send" << msg << "to level 2" << endl;
                    case 3: cout << "Send" << msg << "to level 3" << endl;
                    case 4: cout << "Send" << msg << "to level 4" << endl;
                    case 5: cout << "Send" << msg << "to level 5" << endl;
                    case 6: cout << "Send" << msg << "to level 6" << endl;
                    case 7: cout << "Send" << msg << "to level 7" << endl;
                    case 8: cout << "Send" << msg << "to level 8" << endl;
                    case 9: cout << "Send" << msg << "to level 9" << endl;
                            break;
                    default: cout << "Wrong level!\n" << endl;
                }
                return 0;
            }
            
        

購買票券

            
            #include <iostream>
            #include <cctype>
            using namespace std;

            int main() {
                int price = 500;
                int tickets;
                char credit_card;
                int total;
                int has_card;

                cout << "How many tickets? ";
                cin >> tickets;
                cout << "Do you have a credit card? (Y/n): ";
                cin >> credit_card;

                credit_card = toupper(credit_card);
                has_card = credit_card == 'Y';
                total = has_card ? (int)price*tickets*0.8 : price*tickets;
                cout << "$" << total << " for " << tickets << " tickets." << endl;
                return 0;
            }
            
        

兩層巢狀決策

            
            #include <iostream>
            using namespace std;

            int main() {
                bool furry = true;
                bool small = true;

                if (furry) {
                    if (small)
                        cout << "Cat" << endl;
                    else
                        cout << "Bear" << endl;
                }
                else {
                    if (small)
                        cout << "Gecko" << endl;
                    else
                        cout << "Crocodile" << endl;
                }
                return 0;
            }
            
        

三層巢狀決策(三個孩子)

            
            #include <iostream>
            using namespace std;

            int main() {
                char first_born;
                char second_born;

                cin >> first_born >> second_born;

                if (first_born == 'M') {
                    cout << "1st child: Son" << endl;
                    if (second_born == 'M')
                        cout << "2nd child: Son" << endl;
                    else
                        cout << "2nd child: Daughter" << endl;
                }
                else {
                    cout << "1st child: Daughter" << endl;
                    if (second_born == 'M')
                        cout << "2nd child: Son" << endl;
                    else
                        cout << "2nd child: Daughter" << endl;
                }
                return 0;
            }
            
        

Repetition(重複) - for loop迴圈式(迴圈或重複結構)

五個整數

for (1.迴圈變數預設初值; 2.迴圈可執行條件; 4.迴圈變數遞增遞減) {
    3.迴圈功能程式
}
1->2->3->4->2->3->4...直到 2 的條件不成立
註: 1 只執行一次
            
            #include <iostream>
            using namespace std;

            int main() {
                int i;

                for (i = 0; i < 5; i++) {
                    cout << i << endl;
                }
                return 0;
            }
            
        

五個星號

            
            #include <iostream>
            using namespace std;

            int main() {
                int i;

                for (i = 0; i < 5; i++) {
                    cout << '*' << endl;
                }
                return 0;
            }
            
        

從一到五

            
            #include <iostream>
            using namespace std;

            int main() {
                int i;

                for (i = 1; i < 6; i++) {
                    cout << i << " *" << endl;
                }
                return 0;
            }
            
        

數的兩倍

            
            #include <iostream>
            using namespace std;

            int main() {
                int i;

                for (i = 1; i < 6; i++) {
                    cout << "i: " << i << endl;
                    i = i * 2;
                    cout << "Double of i: " << i << endl;
                }
                return 0;
            }
            
        

大寫小寫

            
            #include <iostream>
            using namespace std;

            int main() {
                char upper = 'A';
                char lower = 'a';
                int i;

                for (i = 0; i < 26; i+=1) {
                    cout << (char)(upper+i) << " ";
                }
                cout << endl;
                for (i = 0; i < 26; i+=1) {
                    cout << (char)(lower+i) << " ";
                }
                cout << endl;
                return 0;
            }
            
        

倒數計時

            
            #include <iostream>
            using namespace std;

            int main() {
                int n = 0;
                int i = 0;

                cout << "n: ";
                cin >> n;
                for (i = n; i >= 1; i--) {
                    cout << i << endl;
                }
                return 0;
            }
            
        

數列三角

            
            #include <iostream>
            using namespace std;

            int main() {
                int n = 0;
                int i = 0, j = 0;

                cout << "n: ";
                cin >> n;
                for (i = 1; i <= n; i++) {
                    for (j = 1; j <= i; j++) {
                        cout << j << " ";
                    }
                    cout << endl;
                }
                return 0;
            }
            
        

星號三角

正左直角、倒左直角、正右直角、倒右直角、金字塔形

            
            #include <iostream>
            using namespace std;

            int main() {
                int n = 0;
                int i = 0, j = 0;

                cout << "n: ";
                cin >> n;
                for (i = 1; i <= n; i++) {
                    for (j = 1; j <= i; j++) {
                        cout << "*";
                    }
                    cout << endl;
                }
                return 0;
            }
            
        

二維轉一維

            
            #include <iostream>
            using namespace std;

            int main() {
                int n;
                int ri, ci, i;

                cout << "2D index -> 1D index" << endl;
                cout << "n: ";
                cin >> n;
                for (ri = 0; ri < n; ri++) {
                    for (ci = 0; ci < n; ci++) {
                        i = ri * n + ci;
                        cout << "ri: " << ri << " "
                             << "ci: " << ci << " -> "
                             << "i: " << i << endl;
                    }
                }
                return 0;
            }
            
        

一維轉二維

            
            #include <iostream>
            #include <cmath>
            using namespace std;

            int main() {
                int n, m;
                int ri, ci, i;

                cout << "2D index -> 1D index" << endl;
                cout << "n: ";
                cin >> n;
                m = (int)sqrt(n);
                cout << "m: " << m << endl;
                for (i = 0; i < n; i++) {
                    ri = i / m;
                    ci = i % m;
                    cout << "ri: " << ri << " "
                         << "ci: " << ci << " <- "
                         << "i: " << i << endl;
                }
                return 0;
            }
            
        

Repetition(重複) - while loop迴圈式(迴圈或重複結構)

整數累加

            
            #include <iostream>
            using namespace std;

            int main() {
                int plus = 1;
                int sum = 0;

                while (plus) {
                    sum = sum + 1;
                    cout << sum << endl;
                    if (sum == 10) {
                        plus = 0;
                    }
                }
                return 0;
            }
            
        

布林變數

            
            #include <iostream>
            using namespace std;

            int main() {
                bool plus = true;
                int sum = 0;

                while (plus) {
                    sum++;
                    cout << sum << endl;
                    if (sum == 10) {
                        plus = false;
                    }
                }
                return 0;
            }
            
        

無條件進迴圈

            
            #include <iostream>
            using namespace std;

            int main() {
                int sum = 0;

                while (true) {
                    sum++;
                    cout << sum << endl;
                    if (sum == 10) {
                        break;
                    }
                }
                return 0;
            }
            
        

非零即真

            
            #include <iostream>
            using namespace std;

            int main() {
                int N = 10;

                while (N) {
                    cout << N << endl;
                    N = N - 1;
                }
                return 0;
            }

            
        

任意數合計

            
            #include <iostream>
            #include <iomanip>
            using namespace std;

            int main() {
                int n = 0;
                int total = 0;
                int i = 1;

                cout << "Enter integers (0 to end):" << endl;
                do {
                    cout << right << setw(2) << i << "> ";
                    cin >> n;
                    while (getchar() != '\n');
                    total += n;
                    i++;
                } while (n != 0);
                cout << "Total: " << total << endl;
                return 0;
            }
            
        

基礎解題操作

基礎解題一

            
            /*
            基礎解題一

            [編譯]
            g++ p1.cpp -o p1
            [執行]
            ./p1 < d1.txt

            [輸入]
            John
            Jane

            */

            #include <bits/stdc++.h>
            using namespace std;

            int main() {
                string name;

                while (cin >> name) {
                    cout << "Hello, " << name << "!" << endl;
                }
                return 0;
            }
            
        

基礎解題二

            
            /*
            基礎解題二

            [編譯]
            g++ p1.cpp -o p1
            [執行]
            ./p1 < d1.txt

            [輸入]
            12 38
            54 87

            */

            #include <bits/stdc++.h>
            using namespace std;

            int main() {
                int a, b;

                while (cin >> a) {
                    cin >> b;
                    cout << a+b << endl;
                }
                return 0;
            }
            
        

基礎解題三

            
            /*
            基礎解題三

            [編譯]
            g++ p1.cpp -o p1
            [執行]
            ./p1 < d1.txt

            [輸入]
            5
            13 24 36 47 18
            4
            32 54 67 81

            */

            #include <bits/stdc++.h>
            using namespace std;

            int main() {
                int n, i, a;
                int total;

                while (cin >> n) {
                    total = 0;
                    for (i = 0; i < n; i+=1) {
                        cin >> a;
                        total += a;
                    }
                    cout << total << endl;
                }
                return 0;
            }
            
        

基礎解題四

            
            /*
            基礎解題四

            [編譯]
            g++ p1.cpp -o p1
            [執行]
            ./p1 < d1.txt

            [輸入]
            3 3
            1 2 3
            6 5 4
            7 8 9
            */

            #include <bits/stdc++.h>
            using namespace std;

            int main() {
                int n, m, a;
                int ri, ci;

                while (cin >> n) {
                    cin >> m;
                    for (ri = 0; ri < n; ri+=1) {
                        for (ci = 0; ci < n; ci+=1) {
                            cin >> a;
                            if (a % 2 == 0) {
                                cout << "O ";
                            }
                            else if (a % 2 == 1) {
                                cout << "X ";
                            }
                        }
                        cout << endl;
                    }
                }
                return 0;
            }
            
        

基礎解題五

            
            /*
            基礎解題五

            [編譯]
            g++ p1.cpp -o p1
            [執行]
            ./p1 < d1.txt

            [輸入]
            AbcDGauGarD

            */

            #include <bits/stdc++.h>
            using namespace std;

            int main() {
                char c;
                int uppers = 0;
                int lowers = 0;

                while (cin >> c) {
                    if (c >= 'A' && c <= 'Z') {
                        uppers += 1;
                    }
                    else if (c >= 'a' && c <= 'z') {
                        lowers += 1;
                    }
                }
                cout << uppers << endl << lowers << endl;
                return 0;
            }