The following code snippet calculates the average of 3 numbers. The average is rounded by different rounding methods.
class AvgNumbers {
private static double roundDouble(double value, int decimalPoints) {
double d = Math.pow(10, decimalPoints);
return Math.round(value * d) / d;
}
public static void main(String[] args) {
// declare variables
double a, b, c, avg;
// initialize variables
a = 11.54;
b = 7.73;
c = 10.54;
avg = (a + b + c) / 3;
System.out.println("Average of " + a + ", " + b + " and " + c + " is: " + avg);
System.out.println("Rounded value:\n"
+ String.format("%1.2f", avg) + "\n"
+ Math.round(avg) + "\n"
+ roundDouble(avg, 2) + "\n");
}
}
Average of 11.54, 7.73 and 10.54 is: 9.936666666666666
Rounded value:
9.94
10
9.94
class AvgNumbers
declares a class named AvgNumbers
.
private static double roundDouble(double value, int decimalPoints)
is a private static method that takes two parameters: value
, which is the number to be rounded, and decimalPoints
, which specifies the number of decimal points to round to. This method uses the Math.round()
function to round the value to the specified number of decimal points. It multiplies the value by 10 raised to the power of decimalPoints
, performs the rounding, and then divides the result by 10 raised to the power of decimalPoints
to obtain the rounded value.
public static void main(String[] args)
is the main method of the program where the execution starts. It takes an array of strings as a parameter (although it is not used in this program).
The following lines declare and initialize variables:
double a, b, c, avg;
a = 11.54;
b = 7.73;
c = 10.54;
Here, a
, b
, and c
are doubles representing the three numbers, and avg
is a double to store the average.
avg = (a + b + c) / 3;
calculates the average of the three numbers by adding them together and dividing the sum by 3. The result is stored in the avg
variable.
The following lines print the average and demonstrate different rounding techniques:
System.out.println("Average of " + a + ", " + b + " and " + c + " is: " + avg);
System.out.println("Rounded value:\n"
+ String.format("%1.2f", avg) + "\n"
+ Math.round(avg) + "\n"
+ roundDouble(avg, 2) + "\n");
The first System.out.println()
statement displays the average value using string concatenation.
The second System.out.println()
statement demonstrates different ways to round the average value:
String.format("%1.2f", avg)
formats the average value with two decimal places using the String.format()
method.Math.round(avg)
rounds the average value to the nearest whole number using the Math.round()
method.roundDouble(avg, 2)
rounds the average value to two decimal places using the roundDouble()
method defined earlier.