Consider the following contract specification for the static method average. Ple
ID: 3781607 • Letter: C
Question
Consider the following contract specification for the static method average. Please note that, both in the specification and in the Java programming language, the integer-division ('/') operator's result is obtained by truncating toward zero. Hence. (-3/2) = -1 and (9/2) = 4. It is like "rounding", except that the quotient given as the result is not necessarily the closest integer to the correct rational quotient: it is the first-encountered integer closer to zero than the correct rational quotient./** Returns the integer average of two given {@code int)s. @param j the first of two integers to average @param k the second of two integers to average @return the integer average of j and k @ensures average = (j + k)/2/public static int average (int j, int k) {...} Answer the following questions. Provide an argument justifying the following claim: The average (as defined here) of two Java ints i and j is representable as an int, regardless of the lower and upper bounds on the value of an int. Provide an implementation of the average method with int as the only type you use (except, perhaps, for boolean).Explanation / Answer
This problem deals with rounding of numbers in Java programmin.
In simple mathematics if we divide 5/2 we get 2.5. If it is rounded of we get 3.
But in progrmming languages the behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.In Java 6 , round(x) is implemented as floor(x+0.5). So to conclude : 2.50 lies between 2.00 and 3.00 it returns the closest even int value, so 2.5 will be 2. 1.50 lies between 1.00 and 2.00.it returns the closest even int value. so 1.5 will be 2.
So, i think this discussion had made you doubts clear and questions understandable.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.