计算数组平均数的Java程序

381 阅读1分钟

编写一个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);
}

image.png

使用while循环计算数组平均值的Java程序

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

在这个Java程序中,我们创建了一个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