Data Types CS Thinking Example 4

Follow the full solution, then compare it with the other examples linked below.

Example 4

hard
A 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. 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. 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