## Complex Mathematical Expressions

1. The C++ Language. Complex. Mathematical. Expressions. Complex Expressions - Struble. 2. Simple Mathematical Expressions. ○ We've seen simple ...

The C++ Language

Complex Mathematical Expressions

Simple Mathematical Expressions !

We've seen simple mathematical expressions – –

!

Special rules – –

! !

2

Only two operands, data being operated on Only one operator, denoting operation to perform Dividing integers Mixing floating point and integer operands

What about more operands and operators? How does mixing data types work? Complex Expressions - Struble

1

Complex Mathematical Expressions !

Suppose you have the statement avgTemp = FREEZE_PT + BOIL_PT / 2.0;

! ! !

Is FREEZE_PT + BOIL_PT calculated first? Or, is BOIL_PT / 2.0 calculated first? In order to answer the question, precedence must be defined for operations.

3

Complex Expressions - Struble

Complex Mathematical Expressions !

4

Precedence rules for C++ Order of evaluation 1)

Operations (from left to right)

2)

Unary +, Unary -

3)

*/%

4)

+-

Expressions in parentheses

Complex Expressions - Struble

2

Complex Mathematical Expressions !

According to precedence rules, BOIL_PT / 2.0 is evaluated first. –

This probably is not what was intended. Instead, write avgTemp = (FREEZE_PT + BOIL_PT) / 2.0;

5

Complex Expressions - Struble

Complex Mathematical Expression ! !

Using precedence, a complex expression can be evaluated as many simple expressions. A useful tool for evaluating complex expressions is an evaluation tree. avgTemp = FREEZE_PT + BOIL_PT / 2.0;

/ +

6

Complex Expressions - Struble

3

Evaluation Tree (Example) avgTemp = FREEZE_PT + BOIL_PT / 2.0;

212.0

-32.0

+

/

2.0

106.0

74.0

7

Complex Expressions - Struble

Evaluation Tree (Example) avgTemp = (FREEZE_PT + BOIL_PT) / 2.0;

-32.0 + 212.0 180.0

/

2.0

90.0

8

Complex Expressions - Struble

4

Evaluation Tree (Example and Exercise) a 7

int a, b, c; double x, y;

b 3

c = a / b + x * y;

x 1.5

y 0.3

c = a / (b + x) * y;

7 / 3 1.5 * 0.3 2 to double 2.0 + 0.45 2.45 to int

9

2

Complex Expressions - Struble

Complex Expressions (Exercises) !

Write C++ expressions for b 2 − 4ac a+b−c a ⋅ −(b + c) a+b c+d 1 1+ y2

10

Complex Expressions - Struble

5

Complex Expressions (Exercises) !

Draw evaluation trees for the following int a, b, c; double x, y, z; a = 3; b = 5; x = 1.3; y = 2.7; z c c z

11

= = = =

a * a + a - x * x + a % (x + y)

b; b + y; b; / a - b * -y;

Complex Expressions - Struble

6