Question:
A math class is using the following method to calculate the average score of its students:
public static double calculateAverage(int[] scores) {
int sum = 0;
for (int i = 0; i < scores.length; i++) {
sum += scores[i];
}
return (double) sum / scores.length;
}
Write a Java method called calculateRoundedAverage
that takes an array of scores as input and returns the rounded average score as an integer. Round the average score to the nearest whole number if the fractional part is less than 0.5, and round up if the fractional part is 0.5 or greater.
You may assume that the input array scores
will always contain at least one element.
Answer:
public static int calculateRoundedAverage(int[] scores) {
int sum = 0;
for (int i = 0; i < scores.length; i++) {
sum += scores[i];
}
double average = (double) sum / scores.length;
int roundedAverage = (int) Math.round(average);
return roundedAverage;
}
Explanation:
The calculateRoundedAverage
method is very similar to the calculateAverage
method provided in the question. It calculates the sum of the scores in the scores
array and then divides it by the length of the array to get the average.
However, in this method, we also calculate a double
value for the average to accommodate for rounding. The Math.round()
method is then used to round this average to the nearest whole number. The rounded average is then cast to an integer and returned as the result.
By using Math.round()
, we ensure that if the fractional part of the average is less than 0.5, it rounds down to the nearest whole number. If the fractional part is 0.5 or greater, it rounds up to the nearest whole number. This matches the rounding behavior described in the question.
Note that we assume the input array scores
will always contain at least one element, so no additional validation is necessary.