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


平均數、中位數和眾數是描述資料集中心趨勢和分佈的關鍵統計量。這些數值有助於理解給定資料的中心趨勢和分佈。在本文中,我們將學習如何在已知給定陣列的中位數和眾數的情況下,使用C++求平均數。

問題陳述

給定一個陣列,我們需要在C++中已知中位數和眾數的情況下求平均數。

示例

    輸入

    [5, 15, 25, 35, 35, 40, 10]
    中位數 = 25
    眾數 = 35

    輸出

    平均數 = 20

暴力方法

在這種方法中,我們透過遍歷陣列來計算平均數。平均數是透過求陣列中所有元素的和併除以元素個數來計算的。

步驟

  • 遍歷陣列並計算所有元素的和。
  • 將總和除以元素個數以求陣列的平均數。
  • 返回陣列的平均數。

實現程式碼

#include 
using namespace std;

// Function to calculate mean
double calculateMean(int arr[], int n) {
    double sum = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
    return sum / n;
}

int main() {
    int arr[] = {5, 15, 25, 35, 35, 40, 10};
    int n = 7;
    double mean = calculateMean(arr, n);
    cout << "The Mean of the given dataset is: " << mean << endl;
    return 0;
}
    
輸出
The Mean of the given dataset is: 23.5714
    
時間複雜度:O(n),因為我們正在遍歷陣列。
空間複雜度:O(1),常數空間。

最佳化方法

在最佳化方法中,我們直接使用公式求平均數,無需遍歷陣列。使用中位數和眾數求平均數的公式是:

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

如果已知中位數和眾數,我們可以簡單地使用此公式求平均數。

步驟

  • 定義一個使用公式求平均數的函式。
  • 此函式將以中位數和眾數為引數,並計算平均數。

實現程式碼

#include 
using namespace std;

// Function to calculate mean using mode and median
double calculateMean(double median, double mode) {
    return (mode + 2 * median) / 3;
}

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

    double mean = calculateMean(median, mode);
    cout << "The Mean of the array is: " << mean << endl;

    return 0;
}
    
輸出
Enter the median of the array: 25
Enter the mode of the array: 35
The Mean of the array is: 20
    
時間複雜度:O(1),常數時間。
空間複雜度:O(1),常數空間。

更新於:2024年11月13日

22 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告