I am having trouble determining how to calculate the median for my array. Additionally, I am not too confident in my solution to find the range of the array. The prompt for my problem is as follows, with my current code below:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A teacher has a small class of 10 students taking an exam. The professor would like to enter the scores from the exam and then calculate the mean, median, and range of scores to display them.
Your job is to write a program that collects the 10 scores using a for loop. Then write a second for loop that calculates the mean, median, and range of the scores.
Finally display the mean, median, and range.
Hint: Use #include <algorithm> to sort() your vector before finding the median.
Example input/output:
Enter the students' 10 scores: 67.0 2.2 73.1 32.2 53.6 41.1 37.9 59.2 69.3 81.6
Mean: 51.72
Median: 56.4
Range: 79.4
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
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
const double NUM_SCORES = 10;
vector<double> studentScores(NUM_SCORES);
int i;
int sum = 0;
int range;
cout << "Enter the students' 10 scores: ";
// determining the sum of the input numbers in the array
for (i = 0; i < studentScores.size(); i++) {
cin >> studentScores.at(i);
sum += studentScores.at(i);
}
// determining the median
double median;
sort(studentScores.begin(), studentScores.end());
if ((studentScores.size() % 2) == 0) {
median = studentScores[studentScores.size() / 2] + studentScores[(studentScores.size() / 2) - 1] / 2;
}
else {
median = studentScores[studentScores.size() / 2];
}
cout << "Mean: " << sum / 10 << endl << "Median: " << median << endl << "Range: " << (studentScores.at(0) - studentScores.at(9)) * -1 << endl;
system("pause");
return 0;
}
|