Well I thought I had this all figured out. Something is wrong with my logic and I can't figure it out. I am supposed to find the median of a group of numbers in a file that I have created (theData.dat), but obviously if there are an even number of integers in the file, it gets a little tricky because you have to pull the two middle numbers from the file and divide them by 2. AND I am just getting used to using while loops. Can someone give me some tips?
Code:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream In;
In.open("theData.dat"); // opens file
int aNumber;
int count = 0;
int median, m1, m2;
int countAgain = 0;
while (In >> aNumber)
{
count++; // counts the number of int in the file
}
In.close(); // allows me to run through the file from the beginning
In.clear();
In.open("theData.dat");
while (In >> aNumber)
{
countAgain++;
if ((count % 2 != 0) && (countAgain == (count + 1 ) / 2))
{
median = aNumber;
}
else
{
while (countAgain == count / 2)
{
m1 = aNumber;
}
while (countAgain == (count + 2) / 2)
{
m2 = aNumber;
}
median = (m1 + m2) / 2.0;
}
}
cout << "The median of this group of numbers is " << median << "." << endl;
return 0;
}