150 likes | 167 Views
Learn how computers perform basic arithmetic with integers and decimals, resolve issues with integer division, and dynamically adjust musical compositions. Focus on order of operations and casting.
E N D
CS111 Intro to Programming Day 7: Using Arithmetic Expressions
Learning Objectives • Understand how computers perform basic arithmetic when using whole numbers (Integers) and decimal numbers (Floats). • Identify and resolve issues with integer division. • Demonstrate basic computer arithmetic by dynamically adjusting a musical composition to fit a specified number of seconds.
The Road Not Taken Computers treat whole numbers and decimal numbers differently. In programming we refer to whole numbers as integers and decimal numbers as floats.
Processing Integers and Floats In the past computers contained a physically separate processor that was optimized for performing floating point arithmetic. Today there is one physical processor, but internally there is a dedicated floating point unit (FPU) that is optimized for the task.
Arithmetic Expressions You should already be familiar with the operators. + - * /
Mathematical Expressions To start, we will focus on integers, not floating points. We know volume of a rectangular prism is equal to length x width x height. length = 10 width = 5 height = 15 volume = length * width * height 750 Right-hand side evaluated first
Mathematical Expressions To start, we will focus on integers, not floating points. To split a package of cookies among friends, we use the equation: # cookies / n. numCookies = 12 numFriends = 6 cookiesPerFriend = numCookies / numFriends 2 RHS evaluated first
Integer Division - Casting If we want to keep the precision, we need to treat the integers as floats, then perform the calculation. numCookies = 12 numFriends = 5 cookiesPerFriend = float(numCookies) / numFriends 2 .4 “cast” numCookies as a float
Order of Operations Evaluated from left to right in order of precedence. What you are used to in math. Can lead to bugs in code ifyou aren’t careful! When in doubt, use parentheses for clarity.
Order of Operations Determine the order of evaluation in the following expressions. • x = a + b + c + d + e • y = a + b * c - d / e • k = a / (b * (c + (d - e)))
Order of Operations Determine the order of evaluation in the following expressions. • x = a + b + c + d + e • y = a + b * c - d / e • k = a / (b * (c + (d - e))) 5 1 2 3 4 5 3 1 4 2 5 4 3 2 1