This website is my last resort. I am working on an assignment for my intro to CS class. I am to write a function that takes two parameters (an array of int and the size of the array). The function should return the median of the array. Array has been sorted using the built-in sort function from the examples in this week's module. Here is my code (so far):
#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;
}
I am submitting the assignment through Mimir and it has now failed the first three submissions, with the following message:
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
I am not entirely sure where the error in my code is that is causing this test failure. Any pointers would be much appreciated! This is an intro class, so I am only allowed to use the methods covered so far (Gaddis Intro to Object-Oriented Programming Chapters 1-8). THANK YOU!
Your findMedian function assumes that the array is already sorted. But the array in the test case that fails isn't.