How to read/understand this line of code.

Here is the program and the line I am wondering about is line 51:

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
  #include <algorithm>
#include <iomanip>
#include <iostream>
#include <ios>
#include <string>
#include <vector>

using namespace std;

int main()
{

	cout << "Please enter your first name: ";
	string name = "";
	cin >> name;
	cout << "Hello, " << name << endl;

	cout << "Please enter your midterm and final exam grades: ";
	double midterm, final = 0.0;
	cin >> midterm >> final;

	cout << "Enter all your homework grades, "
			"followed by end-of-file: ";

	vector<double> homework;
	double x = 0.0;

	while (cin >> x)
	{
		homework.push_back(x);
	}

	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 1;
	}

	sort(homework.begin(), homework.end());

	vec_sz mid = size/2;

	double median = 0.0;

	median = size % 2 == 0 ? (homework[mid] + homework[mid-1] / 2)
			: homework[mid];

	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;
}


I am confused about line 51:

1
2
  median = size % 2 == 0 ? (homework[mid] + homework[mid-1] / 2)
			: homework[mid];



In English, is this code saying: "median either equals (homework[mid] + homework[mid-1] / 2) if size % 2 == 0 or it equals homework[mid]"? Is that how this code is working?
Last edited on
"median either equals (homework[mid] + homework[mid-1] / 2) if size % 2 == 0 or it equals homework[mid]"
Yes, that is what it's saying. It's setting the median to be the average of the two middle-most elements if the size of the vector is even, otherwise just setting it to be the middle element.

It's called the "ternary operator", "ternary if", or "conditional operator"
https://en.wikipedia.org/wiki/%3F:
Last edited on
Line 51 can translate to an if/else construct:
51
52
53
54
55
56
57
58
   if (size % 2 == 0)
   {
      median = homework[mid] + homework[mid - 1] / 2;
   }
   else
   {
      median = homework[mid];
   }

https://www.learncpp.com/cpp-tutorial/34-sizeof-comma-and-conditional-operators/
Topic archived. No new replies allowed.