简体   繁体   English

试图在数组中找到最小值

[英]Attempting to find minimum value in array

I have an array with ten values and I am looking to loop through the array and store the lowest value in a variable but I keep getting 0.0 outputted even though the smallest number is 3 . 我有一个包含十个值的数组,我希望循环遍历数组并将最低值存储在变量中,但即使最小数字为3我仍然会输出0.0

Here is my attempt: 这是我的尝试:

  static void  lowestStudentAvgMark() {
    double [] averagesArray = new double[10];
    for(int i = 0; i < 9; i++) {
      double total = (studentMarksArray[i][0]+studentMarksArray[i][1]+studentMarksArray[i][2])/3;
      averagesArray[i] = total;
    }
    double min = averagesArray[0];
    for (int counter = 1; counter < averagesArray.length; counter++) {
      if (averagesArray[counter] < min) {
        min = averagesArray[counter];
      }
    }
    System.out.println(min);
  }

Your first for loop read 1 less, than actual number. 你的第一个for循环读取比实际数字少1 So, the last index value of averagesArray is 0 . 因此, averagesArray的最后一个索引值为0 So, you got minimum number as 0 . 所以,你得到的最小数字为0

for(int i = 0; i< averagesArray.length; i++){ //Use averagesArray.length

   double total = (studentMarksArray[i][0]+
             studentMarksArray[i][1]+studentMarksArray[i][2])/3;
      averagesArray[i] = total;
}

Use the length of the array to loop- 使用数组的长度循环 -

for(int i = 0; i < averagesArray.length; i++) {

}

It will read from 0 'til the length. 它将从0'开始读取长度。 You used i < 9 when your array has a size of 10. 当阵列的大小为10时,您使用i <9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM