標準函式庫
## C 標準函式庫簡介
C 標準函式庫(C Standard Library)提供許多已經實作好的函式,讓程式可以處理輸入輸出、字串、數學運算、記憶體配置等工作,不必自行從頭撰寫。
使用標準函式庫通常需要:
1. 使用 `#include` 引入標頭檔
2. 呼叫函式庫提供的函式
3. 某些系統可能需要額外連結函式庫
常見標頭檔例如:
| 標頭檔 | 用途 |
|---|---|
| `<stdio.h>` | 輸入與輸出,例如 `printf` |
| `<math.h>` | 數學運算,例如 `sqrt`、`pow` |
| `<string.h>` | 字串處理,例如 `strlen`、`strcpy` |
| `<stdlib.h>` | 記憶體配置、轉換、隨機數等 |
---
## 範例一:使用 `math.h` 計算平方根與次方
```c
#include <stdio.h>
#include <math.h>
int main(void) {
double number = 25.0;
double root = sqrt(number);
double result = pow(2.0, 3.0);
printf("%.2f 的平方根是 %.2f\n", number, root);
printf("2 的 3 次方是 %.2f\n", result);
return 0;
}
```
### 說明
- `sqrt(number)`:計算平方根
- `pow(2.0, 3.0)`:計算次方
- `%.2f`:以小數點後兩位輸出浮點數
- `math.h` 中的函式通常使用 `double` 型別
在部分 GCC 環境中,編譯時需要加上 `-lm`:
```bash
gcc math_example.c -o math_example -lm
```
執行:
```bash
./math_example
```
---
## 範例二:使用 `string.h` 處理字串
```c
#include <stdio.h>
#include <string.h>
int main(void) {
char first[] = "Hello";
char second[] = " World";
char message[50];
strcpy(message, first);
strcat(message, second);
printf("字串內容:%s\n", message);
printf("字串長度:%zu\n", strlen(message));
return 0;
}
```
### 說明
- `strcpy(message, first)`:將 `first` 複製到 `message`
- `strcat(message, second)`:將 `second` 接到 `message` 後面
- `strlen(message)`:計算字串長度
- C 語言字串最後會以特殊字元 `'\0'` 結尾
- `message` 必須有足夠空間,否則可能造成記憶體越界
此程式的輸出類似:
```text
字串內容:Hello World
字串長度:11
```
使用字串函式時,應特別注意陣列大小,避免緩衝區溢位。
相關學習地圖、教學課程
C 語言,系統程式