Simple Arithmateic on a vector

My Problem: I am just passing a small vector into a function. The function's goal is to return the median to main. I have looked over my code and I cannot understand what I have done wrong. I have identified the line I think is the problem. I want this program to out put 5 as it would be the true medain. However, the output is 7 for some reason. Code:

#include <iostream>
#include <vector>

using namespace std;
double median_finder(vector<int> &nums);
int main()
{
vector<int> numbers; //Passing in 4 random ints
numbers.push_back(2);
numbers.push_back(4);
numbers.push_back(6);
numbers.push_back(8);

double med = median_finder(numbers);
cout << med << endl;
}

double median_finder(vector<int> &nums)
{
int first= nums.size()/2;
int second = nums.size()/2+1;
double median = 0;
if ((nums.size()/2) % 2 == 1) //if vector size is odd, take the value in the middle
median = nums[nums.size()/2];
else //if vector size is even, find the average
median = ((nums[first] + nums[second])/2); // This line seems to be the problem!
return median;
}

Wanted Output = 5
Output as is = 7
Last edited on
num[0] is your first element (2)... (6+8)/2 = 7, you seem to expect (4+6)/2 = 5.

Smoke 'em if you got 'em.
Last edited on
Ah! How could I have been so dumb! Thanks very much! However, my program is still not working exactly as I had planned. One more question.If I were to change the vector contents to:
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(4);
numbers.push_back(5);

It gives me the output that my median is 3. Since it is a double, wouldnt it do the math and return the output of 3.5?
I initially was wondering that myself and then found that the problem was the vector index. In order to force division by a double, you could divide by 2.0. Let me know how it goes...

EDIT: I was mistaken, there is no 'd' suffix, just append a '.0'...
Last edited on
Well, I wasnt really sure what you meant, but I was able to fix the problem by changing the entire vector to:

vector<double> numbers;

And then I of course also had to change all the areas I called the vector, but it seems to work as intended now. Thanks a lot for the help!
Yeah, it's because you used to be doing was integer/integer, which returns an int. So seymore wanted you to change the divisor into a float by adding a .0 on the end to make it a float, and thus do floating point division. Although your way works as well, obviously.
Just for the record, adding a decimal point to a numeric literal will make it a double; floats can be made by explicitly appending f.
Topic archived. No new replies allowed.