Reputation: 41
Ok so I created a program that takes in a vector and calculates the median. Although im getting the correct median value for odd number, im not getting the same for even. here is my code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
bool check;
cout<<"Hello World";
vector<double> vec;
vec.push_back(2);
vec.push_back(6);
vec.push_back(8);
vec.push_back(62);
double median;
if(check==vec.size()%2)
{
median=(vec[vec.size() / 2 - 1] + vec[vec.size() / 2]) / 2;
}
else{
median=vec[(vec.size() / 2.0)];
}
cout<<median;
return 0;
}
so when i checked online, the correct answer should be 7 but I get 8.. And this happens only for the even number calculation.. what am i doing wrong i dont get it
Upvotes: 0
Views: 79
Reputation: 945
I rewrote your code and cleaned up some unnecessary variable. I per-calculated the array size n
and the midpoint centerElement
. You do not want to repeatedly do this calculation specially in scenarios where you have a very large array.
I also removed the boolean variable check
, which is completely unnecessary. You can find simply compare the output of modulus operation by comparing it with 0
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<double> vec;
vec.push_back(2);
vec.push_back(6);
vec.push_back(8);
vec.push_back(100);
auto n = vec.size();
auto centerElement = n/2;
double median;
if(n%2 == 0)
{
median=(vec[centerElement - 1] + vec[centerElement]) / 2;
}
else{
median=vec[(centerElement)];
}
cout<<median;
return 0;
}
Upvotes: 1