2 + 3 * 5is evaluated? Do I get 17 or 25? Well, your math classes should've taught you that 17 is the answer, and indeed that's true in C++ as well.
the relative precedence of operators is what determines which operation is performed first.
Since * has a higher precedence than +, the expression 2 + 3 *
5 is evaluated like 2 + (3 * 5).
a / b * c
The associativity of * and / (which both have the same precedence) is
left-to-right, so a / b * c is evaluated as (a
/ b) * c. This can matter in C++. For example, what does
3 / 4 * 1.5 // <--- (3/4)*1.5 = 0*1.5 = 0
evaluate to? If you're not sure, read about type type conversion
covered in the previous lecture.
This table lists the operators and their associativities. They are grouped together on lines with operators of the same precedence, and the lines go from highest precedence at the top, to lowest at the bottom. You should know about precedence and associativity, and you should be able to use tables like this to fix precedence and associativity related bugs, but rely on parentheses when you're unsure.
cout << 3.0 << " percent"
relies on associativity of the << operator to make
sense. Why?
cout << x produces an object (with type and
value!), just as evaluating expressions usually do, and that object is in
fact cout.
Of course, we concentrate on the side effect that evaluating this expression has, which is to send output to standard out. However, the fact that the object produced by the evaluation is actually cout itself is important.
<<
is left associative, i.e. is evaluated left-to-right. So,
cout << 3.0 << " percent" is evaluated as:
(cout << 3.0) << " percent"
In other words,
cout << "percent"
left to evaluate, which has the desired side effect of printing
" percent" to the screen after 3.0.
cin >> expressions work the same way.
a = b = 0
do what you want. Only in this case = is is right-to-left
associative, so we get
a = (b = 0)
The key here is that an assignment
expression evaluates to the value of the left-hand-side object
after the assignment. Therefore:
In C++ (as in English!) "if" is the key to expressing this. The program would be written like the code snippet below. Of course we've got to figure out some C++ that will do the "k is even" for us.
|
What's inside the ()'s in an if statement needs to be an expression
that evaluates to type bool. This is called the test condition.
In particular:
|
|
Now, let's write the C++ code for this test condition.
(k % 2) == 0 is the test condition we need.
Note: A
single "=" in C++ is used for assigning values to variables, a double "="
(i.e. |
==" is an example of a relational operator.
Relational operators make comparisons of their left and right-hand
arguments, and return bool values accordingly. They are:
== (equal), != (not equal), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to)
10:02AM.) Here are two different
solutions to this problem: Version 1 and Version 2.