@nomat,
The median is the "middle" of a sequence of N numbers put in sorted order. Specifically:
- take the middle value if N is odd;
- take the average of the two central values if N is even.
You aren't doing anything like that at the moment. You are merely counting the number of items in the file.
I suggest:
- Read your data into a vector<double>; the size() member function will then tell you N.
- Sort this vector using the sort() algorithm; (your example files are already sorted, but you can't rely on that).
- If N is odd (i.e. N % 2 == 1 ) take the middle value; with integer division (and noting that array indices go from 0 to N-1) this will actually be the N/2 (with deliberate integer division) element;
- If N is even then you want the average of the N/2-1 and N/2 elements (again noting that arrays index from 0 to N-1).
Either change your function to a return type double and return the median, or, as Andy pointed out, pass median by reference. (Personally I would do the former).
Since there are many ways of coming up with an array of elements I would split the reading of a file into a vector and the calculating of a median from a vector into two separate tasks (and hence distinct functions), but it is up to you.
The median of the data in file file1.txt is 40
The median of the data in file file2.txt is 29.5 |