Help me find a median!!!

Hay guys, I am trying to write a program that ask the user how many grades there are, inputs the grades, and displays the median of those grades.
My bubble sort is money but I think my median math is way off because the numbers its throwing out are not right. Then it could be the logic or syntax of my code so any help would be appreciated thanks!!


#include <iostream>
using namespace std;

int numGrd();

void getGrd(double grd[], int sze);

void sortArray(double grd[], int sze);

double median(double grd[], int sze);

void displayGrd(double grd[], int sze); //ignore this, I placed this function to check on my bubble sort, and it is working.

int main()
{
double grd[20], sze; //Set Array
sze = numGrd();

getGrd(grd, sze); // Gets the Grades

sortArray(grd, sze); // Heres my bubble sort

median(grd, sze); //The call to median (this is where my problem is I am sure its my math!!!)

return 0;


}





int numGrd()
{
int sze;
cout << " How many grades? " << endl;
cin >> sze;
return sze;
}

void getGrd(double grd[], int sze)
{
int i;
cout << " Enter Grades " << endl;
for (i = 0; i < sze; i++)
{
cin >> grd[i];
}
}


void sortArray(double grd[], int sze)
{
for (int i = 0; i < sze; i++)
{
for (int j = 0; j < sze - i - 1; j++)
{
if (grd[j] > grd[j + 1])
{
int t = grd[j];
grd[j] = grd[j + 1];
grd[j + 1] = t;
}
}
}
}


double median(double grd[], int sze)
{
double med;
if (sze % 2 == 0) // This is my check to see if even
{
int mid = sze / 2;
med = grd[mid];
}
{ // If odd
int mid1 = sze / 2;
int mid2 = (sze / 2) - 1;
med = (grd[mid1] + grd[mid2]) / 2;
}
cout << "The median grade is " << med << '/n' << endl; //Display median here
return med;

}

void displayGrd(double grd[], int sze)
{
for (int i = 0; i < sze; i++)
cout << grd[i] << ' ' << endl;
}
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/beginner/192613/
Fixed most problems but now its rounding?? Why?? Help!



double median(double grd[], int sze)
{
double med;
if (sze % 2 == 0) // If Even
{
int mid1 = sze / 2;
int mid2 = (sze / 2) - 1;
med = (grd[mid1] + grd[mid2]) / 2;

}
else
{ // Else odd
int mid = sze / 2;
med = grd[mid];
}
cout << "The median grade is " << med << '\n' << endl; //Display median here
return med;

}
closed account (48T7M4Gy)
You should print out the values of mid, mid1 and mid2 as appropriate. You 'll see your calculation for mid2 is wrong. Similarly your calculation for mid is wrong. In both cases the reason is due to the integer division. You need to make adjustments, they aren't complicated.
Last edited on
1
2
3
4
5
6
// invariant: grd != nullptr && sze > 0 && the sequence is_sorted
double median( const double grd[], int sze )
{
    // note: if sze is odd, sze/2 == (sze-1)/2
    return ( grd[ sze/2 ] + grd[ (sze-1)/2 ] ) / 2 ;
}
my temp "t" in my sort was an int, this caused all my problems.
Topic archived. No new replies allowed.