C語言實現輸入不定數量數字並由小到大排列
- ctfm214
- 7月23日
- 讀畢需時 2 分鐘
以下是使用C語言實現輸入不定數量數字並由小到大排列的完整程式:
```c
#include <stdio.h>
#include <stdlib.h>
// 比較函數用於qsort排序
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int main() {
int *numbers = NULL; // 動態數組指針
int capacity = 5; // 初始容量
int count = 0; // 當前元素數量
int input;
// 分配初始內存
numbers = (int*)malloc(capacity * sizeof(int));
if (numbers == NULL) {
printf("內存分配失敗!\n");
return 1;
}
printf("請輸入數字(輸入任意非數字字符結束):\n");
// 持續讀取輸入直到遇到非數字
while (scanf("%d", &input) == 1) {
// 如果數組已滿,擴展容量
if (count >= capacity) {
capacity *= 2; // 容量加倍
int *temp = (int*)realloc(numbers, capacity * sizeof(int));
if (temp == NULL) {
printf("內存擴展失敗!\n");
free(numbers);
return 1;
}
numbers = temp;
}
// 存儲輸入的數字
numbers[count] = input;
count++;
}
// 清除輸入緩衝區
while (getchar() != '\n');
// 檢查是否有輸入數字
if (count == 0) {
printf("未輸入任何數字!\n");
} else {
// 使用快速排序進行排序
qsort(numbers, count, sizeof(int), compare);
// 輸出排序結果
printf("\n排序結果(由小到大):\n");
for (int i = 0; i < count; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
}
// 釋放內存
free(numbers);
return 0;
}
### 程式說明:
1. **動態內存管理**:
- 使用 `malloc` 初始分配空間(5個整數)
- 當空間不足時,使用 `realloc` 加倍容量
- 最後用 `free` 釋放內存
2. **輸入處理**:
- 使用 `scanf` 讀取整數
- 當輸入非數字時自動結束輸入
- 清除輸入緩衝區避免殘留數據
3. **排序算法**:
- 使用標準庫的 `qsort` 快速排序函數
- 自定義比較函數 `compare` 實現升序排序
4. **輸出結果**:
- 顯示排序後的數字序列
- 每數字間用空格分隔
### 使用方式:
1. 編譯程式(Linux/macOS):
```bash
gcc -o sorter sorting.c
```
2. 執行程式:
```bash
./sorter
```
3. 輸入範例:
```
請輸入數字(輸入任意非數字字符結束):
42 17 89 5 23 64 q
```
4. 輸出結果:
```
排序結果(由小到大):
5 17 23 42 64 89
```
### 進階功能擴展建議:
1. **錯誤處理**:
```c
// 在讀取輸入後添加
if (ferror(stdin)) {
printf("輸入錯誤發生!\n");
free(numbers);
return 1;
}
```
2. **降序排序**:
```c
// 修改比較函數
int compare(const void *a, const void *b) {
return (*(int*)b - *(int*)a); // 降序排序
}
```
3. **浮點數支持**:
- 將 `int` 改為 `float`
- 修改 `scanf` 為 `%f`
- 調整比較函數:
```c
int compare(const void *a, const void *b) {
float diff = *(float*)a - *(float*)b;
return (diff > 0) ? 1 : ((diff < 0) ? -1 : 0);
}
```
此程式能高效處理任意數量的輸入數字,並使用優化的快速排序算法進行排序。

留言