Median of Array

So I'm at the end of my program. I'm just trying to finish my function that gets the median of an assortment of integers.

Im just having trouble because it comes back with a very bad number, something like -160008897 and I know it has something to do with my array notation in my formula. Can someone just help me spot it? Let me know if you need the whole program, its long.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void getMedian( int *students, int num_students)
{
	double median;

		if(num_students % 2 !=0)
		{

		median=	((students[num_students]/2) + ((students[num_students]/2) -students[num_students-1])) / 2;

			cout<< "The median of the students surveyed is: "<< median<<endl;

		}
		else
		{
		median=	students[num_students] / 2;
			cout<< "The median of the students surveyed is: "<<median<<endl;
		}
}




Last edited on
couldnt you just do something like
 
median = students[num_students/2 - 1]


ex code:
1
2
3
4
5
6
7
8
9
10
int main()
{
vector<string> students;
    string name;
    int num_students;
    cout << "How many students? " << flush;
    cin >> num_students;
    for(unsigned int i = 0; i<num_students; i++) { cout << "Student " << i+1 << ": " << flush; cin >> name; students.push_back(name); }
    if(num_students % 2 == 0) cout << students[num_students/2 - 1] << endl; else cout << students[num_students/2] << endl;
}
Last edited on
If the number of students is odd, the result is simply the middle element, students[num_students / 2]

If there are an even number, it is the average of the middle two elements
(students[num_students/2] + students[num_students/2-1]) / 2.0
Topic archived. No new replies allowed.