求陣列的最大與最小值是 C 語言最基礎的練習之一。這裡的關鍵觀念是:只需掃過陣列一次,就能同時取得最大值、最小值以及它們的位置,再把兩者互換。
#include <stdio.h>
void change(int a[], int n)
{
int i, maxIdx = 0, minIdx = 0;
for (i = 1; i < n; i++) {
if (a[i] > a[maxIdx]) maxIdx = i;
if (a[i] < a[minIdx]) minIdx = i;
}
int max = a[maxIdx], min = a[minIdx];
a[maxIdx] = min;
a[minIdx] = max;
printf("the position of min is: %3d\n", minIdx);
printf("the position of max is: %3d\n", maxIdx);
printf("Now the array is:\n");
for (i = 0; i < n; i++)
printf("%5d", a[i]);
printf("\nmax=%d\nmin=%d\n", max, min);
}
int main(void)
{
int a[20], i, n;
printf("please input the number of elements:\n");
scanf("%d", &n);
printf("please input the elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
change(a, n);
return 0;
}
網路上流傳的版本常把 max 初始化為 0、min 初始化為 1000,並從 i = 1 開始比較。這種寫法有兩個問題:一旦輸入全為負數或超出預設範圍,結果就會出錯;而且第 0 個元素永遠被跳過。改成用「索引本身」作為比較基準(a[maxIdx]、a[minIdx]),就不需要任何魔法數字,也不會漏掉第一個元素。
另外,原寫法把 max、min 宣告成全域變數,在函式式設計中並非必要;改用區域變數後,函式的副作用只剩下「互換陣列內容」這一件清楚的事。
gcc example.c -o example
./example
please input the number of elements:
3
please input the elements:
1
3
5
the position of min is: 0
the position of max is: 2
Now the array is:
5 3 1
max=5
min=1
順帶一提,stdio.h 是 C 的標準輸出入函式庫,以函式方式對 buffer 讀寫字元;而 C++ 的 iostream.h 引入了串流概念,是以類別方法從 streambuf 中讀寫。兩者不可混用,這也是為什麼純 C 程式裡不需要、也不應該出現 cout。