![](/img/trans.png)
[英]how can I find the lowest value of each row and exclude them to find a new average from array
[英]How to find the lowest value in an array generated from the random class?
我们必须通过一种方法传递数组,该方法采用最高、最低和平均值,然后打印它们。
我在获取分配给 minNum 的最低值时遇到问题。
谢谢!
public static void averageMaxMinMethod(double[] arrayOfDoubles){
double maxNum = 0;
double minNum = 0;
for(int i = 0; i < arrayOfDoubles.length; i++){
if(arrayOfDoubles[i] > maxNum)
maxNum = arrayOfDoubles[i];
if(arrayOfDoubles[i] < minNum)// <=== My poor attempt of getting the lowest value
minNum = arrayOfDoubles[i];
}
System.out.println("Highest given double is: " + maxNum);
System.out.println("Lowest given double is: " + minNum);
}
public static void main(String[] args) {
//1-3: Set up Scanner object to collect user's input on the size of array.
Scanner keyboard = new Scanner(System.in);
System.out.println("How many double numerical entries do you have?");
//4: Declare an array of size sizeOfArray
int sizeOfArray = keyboard.nextInt();
//Initialize array
double[] arrayOfDoubles;
arrayOfDoubles = new double[sizeOfArray];
for(int i = 0; i < sizeOfArray; i++){
//5: Use the Random number Class and walk over the array
Random randomNum = new Random();
arrayOfDoubles[i] = randomNum.nextDouble(0.0 , 100.0);
}
//6: Invoke SumMethod
sumMethod(arrayOfDoubles);
averageMaxMinMethod(arrayOfDoubles);
}
double maxNum = 0;
double minNum = 0;
这仅在最大数量至少为零且最小值至多为零时才有效 - 否则,这些值不会更新。
相反,使用数组中的第一个元素,它至少与最小值一样大,并且至少与最大值一样小。
double maxNum = arrayOfDoubles[0];
double minNum = arrayOfDoubles[0];
其他人指出了您在当前实现中犯的错误,但是您也忘记了计算平均值。 您实际上不必编写代码来执行此操作,Java 包括DoubleSummaryStatistics
可以为您提供max
、 min
和average
。 喜欢,
public static void averageMaxMinMethod(double[] arrayOfDoubles) {
DoubleSummaryStatistics dss = DoubleStream.of(arrayOfDoubles).summaryStatistics();
System.out.println("Highest given double is: " + dss.getMax());
System.out.println("Lowest given double is: " + dss.getMin());
System.out.println("Average is: " + dss.getAverage());
}
如果您需要最大值、最小值和平均值,您可以使用DoubleStream
和DoubleSummaryStatistics
:
double[] arrayOfDoubles = {5.1, 3.7, -2.9, 4.3, -11.2};
DoubleSummaryStatistics statistics = Arrays.stream(arrayOfDoubles).summaryStatistics();
System.out.println("Highest: " + statistics.getMin());
System.out.println("Lowest: " + statistics.getMax());
System.out.println("Average: " + statistics.getAverage());
Output:
Highest: -11.2
Lowest: 5.1
Average: -0.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.