Presentation is loading. Please wait.

Presentation is loading. Please wait.

Boolean Tricks. Expressions in Conditions Condition must evaluate to Boolean but can be arbitrarily complex.

Similar presentations


Presentation on theme: "Boolean Tricks. Expressions in Conditions Condition must evaluate to Boolean but can be arbitrarily complex."— Presentation transcript:

1 Boolean Tricks

2 Expressions in Conditions Condition must evaluate to Boolean but can be arbitrarily complex

3 Expressions in Conditions Condition must evaluate to Boolean but can be arbitrarily complex Just because you can doesn't mean you should. Better:

4 % Check if x is a multiple of y: x % y == 0

5 Even/Odd x % 2 is: – 0  even – 1  odd

6 Comparing Floating Points According to C++: 3.02 != (3 +.01 +.01) Do NOT compare floats directly with == or !=

7 Comparing Floating Points Compare if two floating points are "close enough" |num1 – num2| < threshold

8 Comparing Floating Points Compare if two floating points are "close enough" |num1 – num2| < threshold absolute value: abs(expression) – in threshold – depends on problem, have 15 significant digits to work with

9 Comparing Floating Points

10 Naked Booleans Boolean variable can be used as condition: Same as:

11 ! ! is "not" Preferred to:

12 Problem Want to read in temperature and print "Temp is good" if it is between 68 and 72, or warning if it is too hot/cold.

13 Boolean Flags Flag variable : Boolean used to track condition – Start as true or false – Modify based on eveidence

14 Nested Ifs

15 Nested ifs Conditionals can be "nested"

16 If/Else Matching This code has a logic error:

17 If/Else Matching This code has a logic error:

18 If/Else Matching What computer saw:

19 If/Else Matching { } make ending of if/else explicit Editor will show brace matching Use indentation as visual clue

20 If/Else If can be the body of an else:

21 If/Else if… else if… else if… else form: – More compact/legible – Only one option is chosen

22 Bad If/Else A chain of plain if's not mutually exclusive!

23 Example: Computing Taxes The US federal personal income tax is calculated based on the filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. Read in someone's status and income and determine their tax:

24 Conditions 2 Inputs – Marital status – $ earned 1 Output: tax

25 What happens? No matter what: – Get status – Get income – Print tax Conditionally: – What math to do

26 Step 1 Distinguish based on status

27 Step 2 Refine each category based on earnings:


Download ppt "Boolean Tricks. Expressions in Conditions Condition must evaluate to Boolean but can be arbitrarily complex."

Similar presentations


Ads by Google