Java程序计算数组的平均值

编写一个Java程序,使用for循环计算数组元素的平均值。此示例允许输入数组大小和元素,for循环将迭代每个数组元素并将其添加到arrSum变量中。接下来,我们将该总和除以数组长度或大小。

package RemainingSimplePrograms;

import java.util.Scanner;

public class AverageofArray1 {
	private static Scanner sc;
	public static void main(String[] args) {
		int Size, i;
		double arrSum = 0, arrAvg = 0;
		
		sc = new Scanner(System.in);		
		System.out.print("Enter the Array size = ");
		Size = sc.nextInt();
		
		double[] arr = new double[Size];
		
		System.out.format("Enter Array %d elements  = ", Size);
		for(i = 0; i < Size; i++) 
		{
			arr[i] = sc.nextDouble();
		}
		
		for(i = 0; i < Size; i++) 
		{
			arrSum = arrSum + arr[i];
		}
		arrAvg = arrSum / arr.length;
		
		System.out.format("\nThe Sum of Array Items     = %.2f", arrSum);
		System.out.format("\nThe Average of Array Items = %.2f", arrAvg);
	}
}
Program to Calculate Average of an Array

此程序接受数组元素并使用while循环计算这些值的平均值。

package RemainingSimplePrograms;

import java.util.Scanner;

public class AvgofAr2 {
	private static Scanner sc;
	public static void main(String[] args) {
		int Size, i = 0;
		double arrSum = 0, arrAvg = 0;
		
		sc = new Scanner(System.in);		
		System.out.print("Enter the size = ");
		Size = sc.nextInt();
		
		double[] arr = new double[Size];
		
		System.out.format("Enter %d elements  = ", Size);
		while(i < Size) {
			arr[i] = sc.nextDouble();
			arrSum = arrSum + arr[i];
			i++;
		}
		
		arrAvg = arrSum / Size;
		
		System.out.format("\nThe Sum     = %.2f", arrSum);
		System.out.format("\nThe Average = %.2f", arrAvg);
	}
}
Enter the Size = 5
Enter 5 elements  = 99 122.5 77 149.90 11

The Sum     = 459.40
The Average = 91.88

在此程序中,我们创建了一个calArAv函数,该函数使用do while循环计算数组元素的平均值。

package RemainingSimplePrograms;

import java.util.Scanner;

public class AvgofAr3 {
	private static Scanner sc;
	public static void main(String[] args) {
		int Sz, i = 0;
		
		sc = new Scanner(System.in);		
		System.out.print("Enter the size = ");
		Sz = sc.nextInt();
		
		double[] arr = new double[Sz];
		
		System.out.format("Enter %d elements  = ", Sz);
		do 
		{
			arr[i] = sc.nextDouble();
		} while(++i < Sz);
		
		System.out.format("\nThe Average = %.2f", calArAv(arr, Sz));
	}
	public static double calArAv(double[] arr, int Sz) {
		double arSum = 0, arAg = 0;
		int i = 0;
		
		do 
		{
			arSum = arSum + arr[i];
		} while(++i < Sz);
		
		arAg = arSum / Sz;
		return arAg;
	}
}
Enter the size = 7
Enter 7 elements  = 22 99.4 77.12 128 33.7 150 222.9

The Average = 104.73