第七章第八题(求数组的平均值)(Average the array)

第七章第八题(求数组的平均值)(Average the array)

  • 7.8(求数组的平均值)使用下面的方法头编写两个重载的方法,返回数组的平均数:
    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)
  • 参考代码:
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;
    }
}

  • 结果显示:
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

猜你喜欢

转载自blog.csdn.net/jxh1025_/article/details/109267084
今日推荐