top of page

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);

}

```


此程式能高效處理任意數量的輸入數字,並使用優化的快速排序算法進行排序。

 
 
 

最新文章

查看全部
太子基隆街1號UPPER PRINCE

項目類別 詳細資料 發展商 樂風集團 (LOFTER GROUP) 所在地點 九龍旺角太子基隆街1號 物業類型 單幢式住宅大廈 單位總數 139伙 單位間隔 & 面積 開放式至三房 · 實用面積 192平方呎 至 487平方呎 特色單位 13伙...

 
 
 
藥倍安心系統介紹與爭議分析

以下是關於「藥倍安心」(MediSafe)系統的詳細介紹: **藥倍安心(MediSafe)** 是一款以人工智能驅動的網頁應用程式,由香港聖保羅男女中學中四學生潘浠淳(Clarisse Poon)開發。該系統旨在通過交叉核對醫生處方和病人病歷資料,提高處方準確性和用藥安全...

 
 
 
C语言修改图像颜色方法

在C語言中,改變圖像顏色需要讀取圖像像素數據,修改RGB值後再保存。以下是使用輕量級庫**stb_image**和**stb_image_write**的完整實現: ### 步驟說明 1. 使用`stb_image.h`讀取圖像 2. 修改每個像素的RGB值 3....

 
 
 

留言


© 2023 by Alice Barley. Proudly created with Wix.com

bottom of page