MEDIAN FROM FILE

Sup guys , I'm having trouble with this program question....

Compute the median of a data file. The median is the middle number in a data set. It is the number that has the same number of data elements greater than the number as there are less than the number. Assume that the data is sorted, in increasing order. The median is the middle element of a file if there are an odd number of elements, or the average of the two middle elements if the file has an even number of elements. To do this, you need to read the file, count the number of elements, close the file, and then once again open the file and find the number you need (the middle).

So I wrote my code and I kind of got the basic of the program down, BUT when it comes to odd number of elements, I cant get the median to display as a decimal ! I tried static cast but still no use ... Any help ? I'd appreciate it


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
  #include <iostream>
#include <fstream>

using namespace std;

void createfile();
void countElements();
void median();

int elements;

int main()
{
    countElements();
    median();
    
    
}

void createfile()  // USED TO CREATE THE FILE FIRST
{
    
    ofstream values ("numbers.dat");
    if (values.is_open())
    {
        for(int i = 0; i < 9; i++)
        {
            values << i << endl;
        }
        values.close();
    }
    else
    {
        cout << "Unable to open file." << endl;
    }
}

void countElements() // Tells if its even or odd number of elements
{
    int n;
    
    ifstream values ("numbers.dat");
    if (values.is_open())
    {
        while (values >> n)
        {
            elements++;
        }
        values.close();
    }
    
    
    
}

void median()
{
    int z[100];
    float median;
    
    ifstream values ("numbers.dat");
    if (values.is_open())
    {
       if (elements % 2 == 0) // Even elements
       {
           while (!values.eof())
           {
               for(int j = 0; j < 9; j++)
               {
                   values >> z[j];
               }
           }
           median = static_cast<float>((z[(elements / 2)] + z[(elements / 2) - 1]) / 2);
       }
        else if (elements % 2 != 0) // Odd elements
        {
            while (!values.eof())
            {
                for(int i = 0; i < 9; i++)
                {
                    values >> z[i];
                }
            }
            median = static_cast<float>((z[elements / 2]));
        }
        
    }
    else
    {
        cout << "Error" << endl;
    }
    
    cout << "Median: " << median;
}
Topic archived. No new replies allowed.