- Forward


Rounding
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • The Idea:
    • Sometimes integers have more digits of accuracy than are needed but truncation isn't appropriate
  • An Example:
    • As before, employees are paid a fixed amount per piece, but only for multiples of 10 pieces.
    • But now, to improve employee satisfaction, rounding is used instead of truncation (so 526 pieces will be rounded to 530, not truncated to 520)
Review
Back SMYC Forward
  • Notation:
    • number denotes the value
    • place denotes the place of interest (e.g., 10s, 100s, etc...)
  • Truncation:
    • javaexamples/programmingpatterns/Rounding.java (Fragment: truncated)
       
Thinking About the Problem
Back SMYC Forward
  • The Easy Part:
    • Given the original value, the truncated value, and an appropriate indicator it's easy to find the answer (i.e., increase truncated by place)
  • The Indicator:
    • Involves value - truncated and half of place
The Pattern
Back SMYC Forward
javaexamples/programmingpatterns/Rounding.java (Fragment: pattern)
 
Examples
Back SMYC Forward
  • Code for a Revised Manufacturing Example:
    • javaexamples/programmingpatterns/Rounding.java (Fragment: manufacturingexample)
       
  • Tracing a Revised Manufacturing Example:
    • (number/place)*place is (526/10)*10 or 520
    • number % place is 6
    • place / 2 is 5
    • So, the answer is 520 + 10 or 530
Examples (cont.)
Back SMYC Forward
  • Code for a Revised Year Example:
    • javaexamples/programmingpatterns/Rounding.java (Fragment: yearexample)
       
  • Tracing the Revised Year Example for the Century:
    • (number/place)*place is (2086/100)*100 or 2000
    • num % place is 86
    • 100 / 2 is 50
    • So, the answer is 2000 + 100 or 2100
There's Always More to Learn
Back -