企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Java 程序:使用数组计算平均值 > 原文: [https://beginnersbook.com/2017/09/java-program-to-calculate-average-using-array/](https://beginnersbook.com/2017/09/java-program-to-calculate-average-using-array/) 我们将看到两个使用数组查找数字平均值的程序。第一个程序查找指定数组元素的平均值。第二个程序获取`n`(元素数)的值和用户提供的数字,并使用数组查找它们的平均值。 要了解这些程序,您应该具备以下 [Java 编程](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/)概念的知识: 1) [Java 数组](https://beginnersbook.com/2013/05/java-arrays/) 2) [`For`循环](https://beginnersbook.com/2015/03/for-loop-in-java-with-example/) ## 示例 1:使用数组查找数字平均值 ```java public class JavaExample { public static void main(String[] args) { double[] arr = {19, 12.89, 16.5, 200, 13.7}; double total = 0; for(int i=0; i<arr.length; i++){ total = total + arr[i]; } /* arr.length returns the number of elements * present in the array */ double average = total / arr.length; /* This is used for displaying the formatted output * if you give %.4f then the output would have 4 digits * after decimal point. */ System.out.format("The average is: %.3f", average); } } ``` 输出: ```java The average is: 52.418 ``` ## 示例 2:计算用户输入的数字的平均值 在此示例中,我们使用`Scanner`来获取`n`的值以及来自用户的所有数字。 ```java import java.util.Scanner; public class JavaExample { public static void main(String[] args) { System.out.println("How many numbers you want to enter?"); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); /* Declaring array of n elements, the value * of n is provided by the user */ double[] arr = new double[n]; double total = 0; for(int i=0; i<arr.length; i++){ System.out.print("Enter Element No."+(i+1)+": "); arr[i] = scanner.nextDouble(); } scanner.close(); for(int i=0; i<arr.length; i++){ total = total + arr[i]; } double average = total / arr.length; System.out.format("The average is: %.3f", average); } } ``` **输出:** ```java How many numbers you want to enter? 5 Enter Element No.1: 12.7 Enter Element No.2: 18.9 Enter Element No.3: 20 Enter Element No.4: 13.923 Enter Element No.5: 15.6 The average is: 16.225 ```