要寫一個 C 語言函式 count 計算陣列 score 中不同數值的個數,我們可以採用一種簡單的策略:對陣列進行排序,然後遍歷排序後的陣列,計算不同值的個數。這種方法的關鍵在於排序步驟,它使得相同的數值會被排列在一起,從而可以輕易地通過比較相鄰元素來識別不同的數值。
以下是這個策略的一個實現示例:
c
Copy code
#include <stdio.h>
#include <stdlib.h>
// Function to compare two integers for qsort
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
// count function to calculate the number of unique elements in the array
int count(int score[], int size) {
if (size == 0) return 0; // If the array is empty, return 0
// Sort the array first
qsort(score, size, sizeof(int), compare);
int uniqueCount = 1; // There's at least one unique number if size is not 0
for (int i = 1; i < size; i++) {
if (score[i] != score[i-1]) { // If the current element is different from the previous one
uniqueCount++;
}
}
return uniqueCount;
}
// Example usage
int main() {
int scores[] = {1, 2, 4, 2, 5, 4, 7, 8, 7, 3, 6};
int size = sizeof(scores) / sizeof(scores[0]);
printf("Number of unique values: %d\n", count(scores, size));
return 0;
}
在這個實現中,count 函式首先使用 qsort 函式對 score 陣列進行排序,qsort 是 C 標準函式庫中的快速排序實現。排序後,函式遍歷排序過的陣列,並計算不同數值的個數。當發現當前元素與前一元素不相同時,不同數值的計數器 uniqueCount 就會增加。最後,函式返回計數器的值。