使用者程式碼輸入數字直到 -222 結束,氣泡排序後輸出,要求:
for(i = 0; i < count; i++) {
if ((i + 1) % 5 == 0) {
for (m = -4; m < 1; m++)
printf("%-6d,", array[i + m]);
}
if ((i + 1) % 6 == 0)
printf("%-6d\n", array[i]);
}
嚴重錯誤:當 i = 4, 9, 14... 時,內層迴圈輸出 array[0]~array[4]、array[5]~array[9]...導致 第 5 個元素重複輸出(如 array[4] 輸出兩次)。
#include <stdio.h>
#include <stdlib.h>
#define MAX_N 10000
#define SENTINEL -222
int main() {
int array[MAX_N] = {0};
int count = 0;
int input;
printf("請輸入整數(輸入 %d 結束):\n", SENTINEL);
while (count < MAX_N && scanf("%d", &input) == 1) {
if (input == SENTINEL) break;
array[count++] = input;
}
// 氣泡排序(升序)
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - 1 - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
// 格式化輸出:每 6 個一行
printf("\n排序結果:\n");
for (int i = 0; i < count; i++) {
if ((i + 1) % 6 == 0) {
// 第 6、12、18... 個:印數字 + 換行
printf("%-6d\n", array[i]);
} else {
// 第 1~5、7~11... 個:印數字 + 逗號
printf("%-6d,", array[i]);
}
}
// 若最後一行不滿 6 個,補換行
if (count % 6 != 0) printf("\n");
system("pause");
return 0;
}
輸入:5 2 8 1 9 3 7 4 6 0 -222
排序結果: 0 ,1 ,2 ,3 ,4 ,5 6 ,7 ,8 ,9 , ,
(註:%-6d 靠左對齊寬度 6,若不想要空格可改 %d 配合手動空格)
| 原始錯誤 | 修正做法 | 原理 |
|---|---|---|
雙重條件判斷 %5 與 %6 | 單一 %6 判斷 | 互斥條件:要么是第 6 的倍數(換行),要么不是(加逗號) |
| 內層迴圈重複輸出 | 每個元素僅輸出一次 | 單一迴圈遍歷,每個索引對應一次輸出 |
| 未處理最後一行不滿 6 個 | 迴圈後補 if (count % 6) printf("\n") | 確保游標換行,避免提示符接在數字後 |
#include <stdlib.h>
int cmp_int(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
// 替換氣泡排序部分:
qsort(array, count, sizeof(int), cmp_int);
(i+1) % N 判斷第 N 個元素是經典技巧if-else 而非兩個獨立 if,避免邏輯重疊%-6d 靠左對齊、固定寬度,讓欄位對齊美觀