💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 未排序数组的均值和中位数的程序 > 原文: [https://www.geeksforgeeks.org/program-for-mean-and-median-of-an-unsorted-array/](https://www.geeksforgeeks.org/program-for-mean-and-median-of-an-unsorted-array/) 给定 **n** 大小的未排序数组,找到其均值和中位数。 > **数组的平均值** =(所有元素的总和)/(元素数量) **大小为`n`的排序数组的中位数**当`n`为奇数时定义为中间元素,而当`n`为偶数时定义为中间两个元素的平均值。 由于此处未对数组进行排序,因此我们首先对数组进行排序,然后应用上述公式。 **示例**: ``` Input : a[] = {1, 3, 4, 2, 6, 5, 8, 7} Output : Mean = 4.5 Median = 4.5 Sum of the elements is 1 + 3 + 4 + 2 + 6 + 5 + 8 + 7 = 36 Mean = 36/8 = 4.5 Since number of elements are even, median is average of 4th and 5th largest elements. which means (4 + 5)/2 = 4.5 Input : a[] = {4, 4, 4, 4, 4} Output : Mean = 4 Median = 4 ``` 下面是代码实现: ## C++ ```cpp // CPP program to find mean and median of  // an array #include <bits/stdc++.h> using namespace std; // Function for calculating mean double findMean(int a[], int n) {     int sum = 0;     for (int i = 0; i < n; i++)          sum += a[i];     return (double)sum/(double)n; } // Function for calculating median double findMedian(int a[], int n) {     // First we sort the array     sort(a, a+n);     // check for even case     if (n % 2 != 0)        return (double)a[n/2];     return (double)(a[(n-1)/2] + a[n/2])/2.0; } // Driver program int main() {     int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 };     int n = sizeof(a)/sizeof(a[0]);     cout << "Mean = " << findMean(a, n) << endl;      cout << "Median = " << findMedian(a, n) << endl;      return 0; } ```