Integer CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
mediumA vending machine program stores the price as 175 (meaning $1.75 in cents). A customer inserts 200 cents. Using only integer arithmetic (DIV for integer division, MOD for remainder), calculate the change in dollars and remaining cents.
Solution
- 1 Step 1: change_cents = 200 โ 175 = 25.
- 2 Step 2: dollars = 25 DIV 100 = 0.
- 3 Step 3: cents = 25 MOD 100 = 25.
Answer
Change is 0 dollars and 25 cents. Integer arithmetic avoids the rounding errors that can occur with decimal (floating-point) money calculations.
Storing money as an integer number of cents is a common practice because integer arithmetic is exact, whereas floating-point can produce tiny rounding errors (e.g., 0.1 + 0.2 โ 0.3 in many languages).
About Integer
A data type that represents whole numbers (positive, negative, or zero) without decimal points. Integers are stored exactly in memory and support arithmetic operations like addition, subtraction, multiplication, and integer division.
Learn more about Integer โMore Integer Examples
Example 1 easy
What is the result of integer division [formula] and [formula]? Explain the difference from regular
Example 2 mediumA program stores a student's age as an integer. Why would an integer be more appropriate than a floa
Example 3 easyWhat are the results of: (a) 25 MOD 7, (b) 100 DIV 3, (c) 8 MOD 2?