# C++ 講義:函數、內建函數與自訂函數、全域變數與區域變數 ## 1. 函數 (Functions) 在 C++ 中,函數是一組一起執行一個任務的語句。每個 C++ 程式都至少有一個函數——主函數 `main()`,程序從這裡開始執行。 ### 函數的基本結構: ```cpp 返回類型 函數名稱(參數列表) { // 函數體 } ``` - **返回類型**:函數可以返回一個值。`void` 表示不返回值。 - **函數名稱**:函數的識別符。 - **參數列表**:傳遞給函數的變數,可選。 ### 範例:簡單的函數 ```cpp #include <iostream> using namespace std; // 定義一個函數,計算兩數之和 int add(int a, int b) { return a + b; // 返回兩數之和 } int main() { int sum = add(5, 3); // 調用函數 cout << "Sum is: " << sum << endl; // 輸出結果 return 0; } ``` ## 2. 內建函數 vs. 自訂函數 - **內建函數**:C++ 標準庫提供的函數,如 `std::cout`, `std::endl`, `std::vector::push_back()` 等。 - **自訂函數**:開發者根據需要自己定義的函數。 ### 範例:使用內建函數 ```cpp #include <iostream> #include <cmath> // 包含數學函數庫 using namespace std; int main() { cout << "Square root of 16 is: " << sqrt(16) << endl; // 使用內建函數 sqrt return 0; } ``` ## 3. 全域變數 vs. 區域變數 - **全域變數**:在函數外部定義的變數,可以在程序的任何部分被訪問。 - **區域變數**:在函數內部定義的變數,只能在該函數內部被訪問。 ### 範例:全域變數和區域變數 ```cpp #include <iostream> using namespace std; int globalVar = 20; // 全域變數 void demoFunction() { int localVar = 10; // 區域變數 cout << "Local variable: " << localVar << endl; cout << "Global variable: " << globalVar << endl; } int main() { demoFunction(); cout << "Accessing global variable: " << globalVar << endl; // cout << "Accessing local variable: " << localVar << endl; // 錯誤:localVar 在這裡不可用 return 0; } ``` ## 4. 基礎遞迴 遞迴是在一個函數的定義中調用自身的過程。在許多問題中,遞迴提供了一種更簡潔明了的解決方案。遞迴函數主要由兩部分組成:基底條件(終止條件)和遞迴條件(函數調用自身)。 ### 遞迴的基本結構: ```cpp 返回類型 函數名稱(參數列表) { if (基底條件) { // 基底條件的處理 } else { // 遞迴條件,函數調用自身 } } ``` ### 範例:計算 n 的階乘 ```cpp #include <iostream> using namespace std; // 階乘函數定義 int factorial(int n) { if (n <= 1) { // 基底條件 return 1; } else { // 遞迴條件 return n * factorial(n - 1); } } int main() { int n = 5; cout << "Factorial of " << n << " is: " << factorial(n) << endl; return 0; } ``` ### 小練習:計算 Fibonacci 數列的第 n 項 ` Fibonacci(斐波那契)` 數列是這樣一個數列:每一項都是前兩項之和,且前兩項分別是 0 和 1。 #### 範例輸入: ``` 10 ``` #### 範例輸出: ``` 55 ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up