C++ 從 0 到 1:從變數到位運算
2024-09-11 10:44:03

C++ 程式的基本結構

讓我們從最基本的開始 - 一個簡單的 “Hello World” 程式:

1
2
3
4
5
6
7
#include <iostream>
using namespace std;

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

這個簡單的程式展示了 C++ 的幾個關鍵特性:

  • #include <iostream>: 這行包含了輸入/輸出流套件的載入,為 Input/Output Stream 的縮寫。
  • using namespace std;: 這使我們可以使用 std 命名空間中的對象,如 cout
  • int main(): 這是程式的入口點,也就是程式都會從這邊開始執行
  • cout << "Hello, World!" << endl;: 這行將文本輸出到控制檯。

注釋

C++ 支援兩種類型的注釋:

  1. 單行注釋: 以 // 開始
  2. 多行注釋: 包含在 /**/ 之間

例如:

1
2
3
// 這是一個單行註釋
/* 這是一個
多行注釋 */

注釋對於解釋代碼和提高可讀性非常重要。

變數和資料類型

在 C++ 中,變數是儲存資料的容器。每個變數都有一個特定的資料類型,決定了它可以儲存什麼樣的訊息。

常見資料類型

類型 描述 範例 大小
int 整數 100, -5, 1246 4 bytes
float 浮點數 3.14159f, 4.3f 4 bytes
char 字元 ‘a’, ‘R’, ‘1’ 1 byte
bool 布林值 true, false 1 byte

變數宣告和初始化

變數宣告告訴編譯器變數的名稱和類型。例如:

1
2
3
4
int age;
float pi = 3.14159f;
char grade = 'A';
bool isStudent = true;

你也可以在一行中宣告多個變數:

1
int x = 5, y = 10, z = 15;

變數命名規則

  • 變數名可以包含字母、數字和底線
  • 必須以字母或底線開頭
  • 區分大小寫 (myVar 和 myvar 是不同的變數)
  • 不能包含空格或特殊字元
  • 不能使用 C++ 關鍵字 (如 int, float 等)

輸入和輸出

C++ 使用 iostream 庫進行基本的輸入和輸出操作。

輸出

使用 cout 和流插入運算子 << 進行輸出:

1
cout << "Hello, World!" << endl;

輸入

使用 cin 和流提取運算子 >> 進行輸入:

1
2
3
int age;
cout << "Enter your age: ";
cin >> age;

讀取多個輸入

你可以在一個 cin 語句中讀取多個值:

1
2
3
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;

跳脫序列 Escape sequence

C++ 支援多種跳脫序列,用於表示特殊字元:

序列 描述
\n 換行
\t tab(大約是4個空白鍵)
\ 反斜槓
" 雙引號

例如:

1
cout << "Hello\tWorld!\n";

會輸出:

1
Hello   World!

(注意 “Hello” 和 “World!” 之間的 Tab)

運算子

C++ 提供了各種運算子來執行不同類型的操作。

算術運算子

運算子 描述 例子
+ 加法 a + b
- 減法 a - b
* 乘法 a * b
/ 除法 a / b
% 取餘數 a % b
++ 遞增 a++ 或 ++a
遞減 a– 或 –a

關係運算子

這些運算子傳回布林 Boolen 值 (true 或 false):

運算子 描述 例子
== 等於 x == y
!= 不等於 x != y
> 大於 x > y
< 小於 x < y
>= 大於等於 x >= y
<= 小於等於 x <= y

邏輯運算子

運算子 描述 例子
&& AND (x > 0) && (y < 0)
|| OR (x > 0) || (y < 0)
! NOT !(x > 0)

類型轉換

C++ 支援兩種類型的類型轉換:隱式轉換和顯式轉換。

隱式轉換 Implicit Conversion

編譯器自動執行的轉換,例如:

1
2
int x = 10;
float y = x; // int 隱式轉換為 float

顯式轉換 (類型轉換, Explicit Cast)

程式員明確定義的轉換:

1
2
float x = 3.14;
int y = (int)x; // 顯式將 float 轉換為 int

位元運算

位元運算在底層程式設計和最佳化中非常有用。

位元運算子

運算子 描述 例子
& AND a & b
| OR a | b
^ XOR a ^ b
<< 左移 a << 2
>> 右移 a >> 2
~ NOT ~a

使用位元運算的例子

  1. 檢查數字是否為偶數:

    1
    2
    3
    bool isEven(int n) {
    return !(n & 1);
    }
  2. 使用位元運算交換兩個變數的值:

    1
    2
    3
    4
    5
    void swapUsingXOR(int &a, int &b) {
    a ^= b;
    b ^= a;
    a ^= b;
    }
  3. 使用位元移計算 2 的冪(exponentiation):

    1
    2
    3
    int powerOfTwo(int n) {
    return 1 << n;
    }

實踐練習

挑戰 1:溫度轉換器

目標: 建立一個程式,可以在攝氏度和華氏度之間進行溫度轉換。

任務:

  1. 提示使用者輸入一個溫度值。
  2. 詢問使用者這個溫度是攝氏度還是華氏度。
  3. 將溫度轉換為另一種單位。
  4. 顯示轉換結果,精確到小數點後兩位。

提示:

  • 攝氏度到華氏度的公式:°F = (°C × 9/5) + 32
  • 華氏度到攝氏度的公式:°C = (°F - 32) × 5/9

範常式式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
double temperature;
char unit;

cout << "Enter the temperature: ";
cin >> temperature;

cout << "Enter the unit (C for Celsius, F for Fahrenheit): ";
cin >> unit;

if (unit == 'C' || unit == 'c') {
double fahrenheit = (temperature * 9/5) + 32;
cout << fixed << setprecision(2);
cout << temperature << "°C is " << fahrenheit << "°F" << endl;
} else if (unit == 'F' || unit == 'f') {
double celsius = (temperature - 32) * 5/9;
cout << fixed << setprecision(2);
cout << temperature << "°F is " << celsius << "°C" << endl;
} else {
cout << "Invalid unit entered!" << endl;
}

return 0;
}

挑戰 2:二進制數轉換器

目標: 編寫一個程式,將使用者輸入的十進制數轉換為二進制數。

任務:

  1. 提示使用者輸入一個非負整數。
  2. 將該整數轉換為其二進製表示。
  3. 顯示轉換結果。

提示:

  • 使用位元運算和移位元運算可以高效地完成這個任務。
  • 考慮如何處理 0 這個特殊情況。

範常式式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <vector>
using namespace std;

int main() {
int number;
vector<int> binary;

cout << "Enter a non-negative integer: ";
cin >> number;

if (number == 0) {
cout << "Binary representation: 0" << endl;
return 0;
}

while (number > 0) {
binary.push_back(number & 1);
number >>= 1;
}

cout << "Binary representation: ";
for (int i = binary.size() - 1; i >= 0; i--) {
cout << binary[i];
}
cout << endl;

return 0;
}

挑戰 3:簡單加密器

目標: 建立一個程式,可以對輸入的文本進行簡單的加密和解密。

任務:

  1. 提示使用者輸入一段文本。
  2. 詢問使用者是要加密還是解密。
  3. 對每個字元進行移位元運算(例如,將每個字元的 ASCII 值加 3 進行加密,減 3 進行解密)。
  4. 顯示處理後的結果。

提示:

  • 使用 Caesar 密碼的概念,但只對字母進行操作。
  • 記得處理大小寫字母和字母表的迴圈(例如,’Z’ 加 1 應該變成 ‘A’)。

範例程式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
using namespace std;

string caesarCipher(string text, int shift, bool encrypt) {
string result = "";
for (char& c : text) {
if (isalpha(c)) {
char base = isupper(c) ? 'A' : 'a';
c = base + (c - base + (encrypt ? shift : 26 - shift)) % 26;
}
result += c;
}
return result;
}

int main() {
string text;
char choice;
int shift = 3; // 使用固定的移位值,你也可以讓使用者輸入

cout << "Enter the text: ";
getline(cin, text);

cout << "Enter 'E' for encrypt or 'D' for decrypt: ";
cin >> choice;

if (toupper(choice) == 'E') {
cout << "Encrypted text: " << caesarCipher(text, shift, true) << endl;
} else if (toupper(choice) == 'D') {
cout << "Decrypted text: " << caesarCipher(text, shift, false) << endl;
} else {
cout << "Invalid choice!" << endl;
}

return 0;
}
Prev
2024-09-11 10:44:03
Next