Chapter 7 Question 8 (Average the array) (Average the array)

Chapter 7 Question 8 (Average the array) (Average the array)

  • 7.8 (Find the average of the array) Use the following method to write two overloaded methods to return the average of the array:
    public static int average(int[] array)
    public static double average(double[] array)
    7.8(Average the array) Write two overloaded methods using the following method headers to return the average of the array:
    public static int average(int[] array)
    public static double average(double[] array)
  • Reference Code:
package chapter07;

import java.util.Scanner;

public class Code_08 {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.print("Enter 10 double numbers: ");
        double[] array = new double[10];
        for (int i = 0;i < array.length;i++)
            array[i] = input.nextDouble();
        System.out.print("The average is " + average(array));
    }
    public static int average(int[] array){
    
    
        int sum = 0;
        for (int i : array)
            sum += i;
        return sum / array.length;
    }
    public static double average(double[] array){
    
    
        double sum = 0;
        for (double i : array)
            sum += i;
        return sum / array.length;
    }
}

  • The results show that:
Enter 10 double numbers: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.0
The average is 5.95
Process finished with exit code 0

Guess you like

Origin blog.csdn.net/jxh1025_/article/details/109267084