本文目录一览:
- 1、java编程求数组的平均数
- 2、用JAVA求平均值
- 3、Java数组求平均数
java编程求数组的平均数
public class aveage {
public static void main(String[] args) {
int[] arrary1 = { 12,4,54,6,78,98,48,787,456 };
double x = ave(arrary1);
System.out.println("平均数为" + x);
}
static double ave(int[] a) {
int sum = 0;
for (int i = 0; i a.length; i++) {
sum += a[i];//累加求和
}
return sum*1.0/a.length;//求平均数
// *1.0的左右,就是把结果类型变成double类型
}
}
用JAVA求平均值
package test;
import java.util.List;
public interface Average{
public double getAverage(ListDouble list);
}
package test;
import java.util.List;
public class First implements Average {
public double getAverage(ListDouble list) {
double sum = 0;
for(int i=0;ilist.size();i++){
sum += list.get(i).doubleValue();
}
return sum / list.size();
}
}
package test;
import java.util.Collections;
import java.util.List;
public class Second implements Average {
public double getAverage(ListDouble list) {
Collections.sort(list);
double sum = 0;
for(int i=1;ilist.size()-1;i++){
sum += list.get(i).doubleValue();
}
return sum / (list.size() - 2);
}
}
package test;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args){
ListDouble list = new ArrayListDouble();
list.add(50d);
list.add(48d);
list.add(20d);
list.add(51d);
list.add(36d);
Average first = new First();
Average second = new Second();
System.out.println(first.getAverage(list));
System.out.println(second.getAverage(list));
}
}
为了测试,我只输入了5个数,录入的代码网上很多,算法给出了,祝你好运。
Java数组求平均数
public
static
void
main(String[]
args){
double[]
array=new
double[10];
double
ave=0;
double
sum=0;
Scanner
input=new
Scanner(System.in);
for(int
i=0;iarray.length;i++){
array[i]=input.nextDouble();
sum+=array[i];
}
ave=sum/array.length;
System.out.println("平均数为:"+ave);
}