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