This code is correct it runs correctly I just have a question about something pertaining to the median. It says near the bottom of my code that mid is equal to size / 2. but from my understanding since size is representing homework.size()
wouldn't half of it be half of the amount of elements in the vector not half of the sum of the elements within the vectors. I hope I made that question as clear as possible, by the way the goal of this code is to compute a final grade.
#include <iostream>
#include <ios>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
usingnamespace std;
int main()
{
//ask for and read the student's name
cout << "Please enter your name: ";
string name;
cin >> name;
cout << "Hello, " + name + "!";
cout << endl;
//ask for and read the midterm and final grades
cout << "Please enter your midterm and final grades: ";
double midterm, final;
cin >> midterm >> final;
//ask for and read the homework grades
cout << "Enter all of your homework grades, ""followed by end_of_file: ";
//vector is a container that holds values
//so this vector will hold numbers with decimals because it's type is "double"
vector<double> homework;
double x;
//invariant: homework contains all the homework grades read so far
while (cin >> x)
//push_back can only be used with vectors, it is pushing 1 data into the
//vector or container until it hits EOF or the data does not fit the type. because it
//is pushing this data into the vector, as a side effect it will increase the vectors size by 1.
homework.push_back(x);
//check that the student entered some homework grades
//typedef allows you to use the name that we define to be a synonym for the given type
//so for example vec_sz = vector<double>::size_type
typedef vector<double>::size_type vec_sz;
vec_sz size = homework.size();
if (size == 0) {
cout << endl << "You must enter your grades. ""Please try again. " << endl;
return 1000000;
}
//sort the grades
sort(homework.begin(), homework.end());
//compute the median homework grade
vec_sz mid = size/2;
double median;
median = size % 2 == 0 ? (homework[mid] + homework[mid-1]) / 2
: homework[mid];
//compute and write the final grade
streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3)
<< 0.2 * midterm + 0.4 * final + 0.4 * median
<< setprecision(prec) << endl;
return 0;
}