繁体   English   中英

在数组中查找 max 和 min 的索引

[英]finding the index of max and min in an array

这是我的代码。 我正在使用 bluej IDE。

    public class practice
    {
public int[] minMax(int[] num) {  
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i <= num.length - 1; i++){
    if (num[i] < smallest) smallest = num[i];
    if (num[i] > largest) largest = num[i];
}
for (int i = 0; i <= num.length - 1; i++){
    if (num[i] != smallest) countsmall++;
    if (num[i] != largest) countlarge++;
}
int array[] = {countsmall,countlarge};
return array;
}
}

我试图在我成功完成的数组中找到最小值和最大值。 之后,我试图找到它的索引。 我创建了一个变量计数,然后遍历了数组。 如果数组中的该项不等于最小值或最大值,则 count+= count。 但是,由于某种原因,它不起作用。 代码编译但返回错误的值。 请记住,我不允许使用 java 库。 任何帮助将不胜感激,谢谢。

如果您还想要最大和最小的索引,为什么不在一个循环中执行呢? 例如:

public class practice
{
    public int[] minMax(int[] num) {  
      int smallest = num[0];
      int largest = num[0];
      int countsmall = 0;
      int countlarge = 0;
      for (int i = 0; i < num.length; i++){
        if (num[i] < smallest) {
            smallest = num[i];
            countsmall=i;
        }
        if (num[i] > largest) {
            largest = num[i];
            countlarge=i;
        }
      }
    
      int array[] = {countsmall,countlarge};
      return array;
    }
}

暂无
暂无

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

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