case'M':
case'm':
int j;
int size;
double average, median;
if(i == 0)
{
cout << "ERROR" << endl;
break;
}
j = size / 2.0;
if (size % 2)
{
median = (aArray[j] + aArray[j + 1]) / 2.0;
cout << "The median is: " << average << endl;
}
else
{
median = aArray[j + 0] / 1.0;
cout << "The median is: " << median << endl;
}
break;
I have this case where I am trying to find the median of an array but it is not working can someone tell me why. If you need my entire code let me know.
size % 2 is true when size is odd. When there are an odd number of elements in a sequence, the median is one element of the sequence, not the average of two of elements.
When the number of elements in a (sorted) sequence is even, the median is the average of the elements indexed by size/2 and size/2-1.
It hasn't worked. For this program we are inputting numbers and storing them into the array. I've inputted 2,2,3,5,6. The median should be 3 but it says that it is 0 and 2.
I have been presuming there was more code in there that you didn't post here. In the latest code you've posted here, num is uninitialized and contains no specific value. It does not represent the number of elements in the array.
In the PM, you suffer from the same problem you do in the code you posted here. num does not represent the number of elements in the array. It has some random value. The number of elements in the array seem to be represented by a generically named variable i.
Replacing int num; with int num=i; would probably do the trick for you.