计算一个数与一组数字中的哪一个数字大小最接近(数字择优)

 1 /**
 2      *   计算一个数与一组数字中的哪一个数字大小最接近
 3      * @param re
 4      * @param ble
 5      * @return
 6      */
 7     public static int choicePreset(int[] re,int ble) {
 8         //1.存差值的绝对值
 9         int[] result=new int[re.length];
10         //2.存差值对应的数字
11         Map<Integer, Integer> map=new HashMap<>();
12         int min=0;
13         for (int i=0;i<re.length;i++) { 
14             //3.计算出这两个数字之间的差,绝对值
15             min=Math.abs(re[i]-ble);
16             result[i]=min;
17             map.put(min, re[i]);
18         }
19         //对差值的绝对值排序
20         Arrays.sort(result); 
21         //返回与ble差值最小一个数
22         return    map.get(result[0]);
23     }
public static void main(String[] args) throws InterruptedException {
        int[] re= {1,5,6,9,25,36,95,64,23};
        int ble=96;
        System.out.println(choicePreset(re, ble));
}

猜你喜欢

转载自blog.csdn.net/waiting233/article/details/117600283