在 C++ 数组中查找中位数(双精度)?

Finding a median (double) in C++ Array?

这个网站是我最后的选择。我正在为我的 CS class 介绍作业。我要编写一个带有两个参数的函数(一个 int 数组和数组的大小)。该函数应该 return 数组的中位数。已使用本周模块示例中的内置排序函数对数组进行排序。这是我的代码(到目前为止):

#include<iostream>
#include<algorithm>
using std::cout;
using std::endl;

//Function prototype
double findMedian(int array[], int size);

//Main function
int main()
{
    int array[] = {23, 5, -10, 0, 0, 321, 1, 2, 99, 30};
    int size = 10;

    //Function to sort array smallest to largest
    std::sort(array, array + size);
    for(int i = 0; i < size; i++)
       std::cout << array[i] << ' ' ;

    //Call to findMedian function
    double median = findMedian(array, size);

    //Output median of the array
    std::cout << "\nMedian is: " << median << std::endl;

    return 0;
}

//Function to calculate median of sorted array
double findMedian(int array[], int size)
{
    double median = 0.0;

    if(size % 2 == 0) //If array size is even
    {
        median = (array[(size-1)/2] + array[size/2])/2.0;
    }
    else //If array size is odd
    {
    median = array[size/2];
    }
    return median;
}

我正在通过 Mimir 提交作业,现在前三个提交都失败了,并显示以下消息:

INPUT OF THE TEST CASE 
#include <cmath>
const double EPS = 0.00001;

int array[] = {1,5,7,4,2,6,3,9,8};
double result = findMedian(array, 9);
ASSERT_TRUE(fabs(result-5.0) < EPS);


YOUR CODE'S OUTPUT 
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from MimirTest
[ RUN      ] MimirTest.cppUnitTest
tests.cpp:24: Failure
Value of: fabs(result-5.0) < EPS
  Actual: false
Expected: true
[  FAILED  ] MimirTest.cppUnitTest (0 ms)
[----------] 1 test from MimirTest (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] MimirTest.cppUnitTest

1 FAILED TEST

我不完全确定我的代码中的错误是什么导致了这次测试失败。任何指针将不胜感激!这是一个介绍 class,所以我只能使用目前为止涵盖的方法(Gaddis Intro to Object-Oriented Programming Chapters 1-8)。谢谢!

您的 findMedian 函数假定数组已经排序。但是失败的测试用例中的数组不是。