Data Types CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
hardA program stores prices as integers in pence (e.g., 499 for ยฃ4.99) rather than as floats. Explain two advantages of this approach.
Solution
- 1 Step 1: Floating-point arithmetic can produce rounding errors (e.g., 0.1 + 0.2 = 0.30000000000000004), which is unacceptable for financial calculations.
- 2 Step 2: Integer arithmetic is exact and faster. Storing in pence avoids precision issues while still representing all values accurately.
Answer
Advantages: (1) avoids floating-point rounding errors, (2) integer arithmetic is exact and more efficient for financial calculations.
Financial software commonly stores monetary values as integers in the smallest unit (pence, cents) to guarantee precision. This is a real-world application of understanding data type limitations.
About Data Types
Categories that classify data values and determine which operations can validly be performed on them. Common data types include integers, floating-point numbers, strings, booleans, and arrays, each with its own set of permitted operations.
Learn more about Data Types โMore Data Types Examples
Example 1 easy
Classify each value into its data type: (a) 42, (b) 'Hello', (c) 3.14, (d) TRUE.
Example 2 mediumA program reads user input as a string '25'. What happens if you try to calculate '25' + 10 without
Example 3 mediumFor each scenario, choose the most appropriate data type: (a) a student's name, (b) number of studen