一、使用 C 語言,寫一個叫做 count()的函式,此函式有 2 個參數,一個是整數陣列 score,另一個是代表陣列大小的整數 size。假設 score 陣列的所有元素都有整數值, 此函式將計算陣列內有多少個不同的數值,並將其傳回。(25 分)
詳解 (共 2 筆)
詳解
要寫一個 C 語言函式 count 計算陣列 score 中不同數值的個數,我們可以採用一種簡單的策略:對陣列進行排序,然後遍歷排序後的陣列,計算不同值的個數。這種方法的關鍵在於排序步驟,它使得相同的數值會被排列在一起,從而可以輕易地通過比較相鄰元素來識別不同的數值。
以下是這個策略的一個實現示例:
c
Copy code
#include <stdio.h>
#include <stdlib.h>
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);
}
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;
}
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 就會增加。最後,函式返回計數器的值。
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 就會增加。最後,函式返回計數器的值。
詳解
int count(int score[], int size){
int count = 0;
for(int i = 0 ; i <size; i++){
int j = 0;
while(j < i){
if(score[i] == score[j])
break;
j++;
}
if(i == j){
count ++;
}
}
return count;
}