C++ 中已知陣列的平均數和眾數求中位數的程式


平均數、中位數和眾數是描述資料集中趨勢和離散程度的基本統計量。這三個量有助於理解資料的整體分佈。本文將學習如何在已知 C++ 中 陣列 的平均數和眾數的情況下找到中位數。

問題陳述

給定一個數字陣列,我們需要計算中位數,前提是在 C++ 中已知陣列的平均數和眾數。

示例

輸入

[5, 15, 25, 35, 35, 40, 10]
平均數 = 20
眾數 = 35

輸出

Median = 25

暴力法

在暴力法中,我們首先對陣列進行排序,然後找到中間元素來計算中位數。如果陣列中的元素個數為奇數,則直接返回中間元素作為中位數;如果元素個數為偶數,則中位數為兩個中間元素的平均值。

步驟

  • 我們首先將陣列按升序排序。
  • 現在,我們檢查元素個數是奇數還是偶數。
  • 如果元素個數為奇數,則中間元素為中位數。
  • 如果元素個數為偶數,則我們計算兩個中間元素的平均值。
  • 返回計算出的中位數。

程式碼實現

以下是上述問題陳述的程式碼實現

#include <bits/stdc++.h>
using namespace std;

// Function
double calculateMedian(int arr[], int n) {
    sort(arr, arr + n);
    if (n % 2 != 0) {
        return arr[n / 2];
    } else {
        return (arr[(n - 1) / 2] + arr[n / 2]) / 2.0;
    }
}

int main() {
    int arr[] = {5, 15, 25, 35, 35, 40, 10};
    int n = 7;
    double median = calculateMedian(arr, n);
    cout << "The Median of the given dataset is: " << median << endl;
    return 0;
}

輸出

The Median of the given dataset is: 25

時間複雜度:O(n log n),因為我們對陣列進行了排序。
空間複雜度:O(1),常數空間

最佳化方法

如果我們想找到陣列的中位數,如果給定陣列的平均數和眾數,我們可以使用直接公式。這是查詢陣列中位數的最簡單方法。當已知平均數和眾數時,計算中位數的公式為

中位數 = (3 × 平均數 − 眾數) / 2

如果給定平均數和眾數,我們可以使用上述公式計算中位數。

步驟

  • 我們定義一個函式來計算中位數。
  • 我們將平均數和眾數的值傳遞給此函式。
  • 現在,我們使用公式計算中位數:中位數 = (3 × 平均數 − 眾數) / 2
  • 返回計算出的中位數。

程式碼實現

#include <bits/stdc++.h>
using namespace std;

// Function
double calculateMedian(double mean, double mode) {
    return (3 * mean - mode) / 2;
}

int main() {
    double mean, mode;
    cout << "Enter the mean of the array: ";
    cin >> mean;
    cout << "Enter the mode of the array: ";
    cin >> mode;

    double median = calculateMedian(mean, mode);

    // Output the result
    cout << "The Median of the array is: " << median << endl;
    return 0;
}

輸出

Enter the mean of the array: 20
Enter the mode of the array: 35
The Median of the array is: 25

時間複雜度:O(1),常數時間。
空間複雜度:O(1),常數空間。

更新於: 2024-11-13

16 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

立即開始
廣告