SOMEBODY PLEASE HELP!

This program is suppose to calculate the median from a file containing 14 integers separated by spaces. The program doesn't work, it output a negative number as a median. please help.

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
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

void read_file(ifstream& fin1, int& count11);
//reads the file and calculates the location of the median.

void calc_median(ifstream& fin2, int& count);
//Calculates the median and displays it.

int main()
{
    ifstream in_stream;
    int number, count1 = 0;
    double median;
    
    read_file(in_stream, count1);
    calc_median(in_stream, count1);
    
    in_stream.close();
    
    cout << endl <<endl;
    
    system("PAUSE");
    
    return 0;
}
 
void read_file(ifstream& fin1, int& count11)
{
     int num = 0;
     count11 =0;
         
     fin1.open("myMedian.txt");
     if(fin1.fail())
     {
        cout << "Input file failed to open" <<endl;
        exit(1);
     }
     
     do
     {
         fin1 >> num;
         count11++;
     }while(!fin1.eof());
     fin1.close();
}

void calc_median(ifstream& fin2, int& count)
{     
     int location = 0, numbers[count], median, num; 
     
     fin2.open("myMedian.txt");
     if(fin2.fail())
     {
        cout << "File opening failed"<<endl;
        exit(1);
     }
     
     if(count%2 == 0)
     {
        location = count / 2;
        for(int i = 0; i < count; i++)
        {
           fin2 >> num;
           numbers[i] = num;
        }
        median = (numbers[location] + numbers[location + 1])/2;
     }
     else
         median = numbers[location + 1];
         
     cout << "The median is equal to: "<< median <<endl;
     
}
Last edited on
is there any negative value in the file ?
No, there is no negative number in the file.
If count is 14 count%2 == 0 is false so the the else part in calc_median will run: median = numbers[location + 1]; Problem here is that location is still zero and you have not written anything to the array so it will only contain garbage values, possibly negative.
thank you for your response Peter87, but i thought the line numbers[i] = num; in calc_median function writes into the array.
Yes but only if count is odd.
Isn't count%2 == 0 true for count an even number?

My test loops through the else branch in calc_median since for an input file of 14 integers count1 after read_file is 15.

vin, you are right. But if the count variable is wrong it is still the same problem. looping until .eof() often do one iteration too much. Try replace the do-while loop in read_file with:
1
2
3
4
while(fin1 >> num)
{
    count11++;
}

Topic archived. No new replies allowed.