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.
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;
}
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.