The average of three byte values
No. 227
Q: |
A newbie programmer codes the following snippet:
A senior programmer warns about two possible problems:
Explain both points in the answer box below. Then provide an improved implementation in the answer box. Do this without changing the method's signature . Tip
|
||||||||||||
A: |
Solving these flaws requires using a data type behaving free
of overflow errors with respect to the given context of summing up
three byte values. Choosing Dividing by 3 should be a floating point rather than an
integer operation to avoid cutting off fractional values. We
subsequently use the Finally we need a cast for converting back the rounded
value's type
Given that our variable sum will always stay within range
[-3 * -128, 3 * 127] dividing by three guarantees |