Getting the Average of two numbers in Java is easy. Below is the function that calculates the average of two double numbers that are passed to it as parameters.
How to calculate the average of two numbers in Java?
public static double GetAvarage(double number1, double number2) { double sum, avarage; sum = number1 + number2; avarage = sum / 2; return avarage; }
Now call this function from the main function:
public static void main(String[] args) { // Declare two numbers double num1, num2; // Initialize the two numebrs num1 = 12; num2 = 17; // Display the average System.out.println("The average is: " + GetAvarage(num1, num2)); }
Output
The average is: 14.5
Happy coding!
IT specialist Veteran