我的ListDoubles

List<Double>  aList = Arrays.asList(100.33,300.99,600.0,900.44,1200.88,1500.15);


我需要从该列表中找到给定值的最接近值。我尝试了以下来自SO另一个答案的解决方案,但到目前为止这仍然行不通,idx始终为0。

以下是我正在检查的解决方案:

private Double chekcer() {
    int myNumber = 900;
    double distance = (aList.get(0)- myNumber);
    int idx = 0;
    for (int c = 1; c < aList.size(); c++) {
        double cdistance = (aList.get(c) - myNumber);
        if (cdistance < distance) {
            idx = c;
            distance = cdistance;
        }
    }
    Log("",...);
    return aList.get(idx);
}

最佳答案

您应该使用差的绝对值,并且它可能大于或小于0

尝试

private Double chekcer() {
  int myNumber = 900;
  double distance = Math.abs(aList.get(0)- myNumber);
  int idx = 0;
  for (int c = 1; c < aList.size(); c++) {
    double cdistance = Math.abs(aList.get(c) - myNumber);
    if (cdistance < distance) {
        idx = c;
        distance = cdistance;
    }
  }
  Log("",...);
  return aList.get(idx);
}


编辑

这是我的全部代码,

public static void main(String[] args)  {

    System.out.println(chekcer());
}

private static Double chekcer() {
      List<Double>  aList = Arrays.asList(100.33,300.99,600.0,900.44,1200.88,1500.15);
      int myNumber = 900;
      double distance = Math.abs(aList.get(0)- myNumber);
      int idx = 0;
      for (int c = 1; c < aList.size(); c++) {
        double cdistance = Math.abs(aList.get(c) - myNumber);
        if (cdistance < distance) {
            idx = c;
            distance = cdistance;
        }
      }
      return aList.get(idx);
    }


输出

900.44

关于java - 从 double 数字列表中获取给定值的最接近索引值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57703694/

10-13 01:55