java获取最接近的数值

java获取最接近的数值

//获取接近值
    private static long getApproximateValue(Long x, Long[] source) {
        if (source == null) {
            return -1;
        }
        if (source.length == 1) {
            return source[0];
        }
        long minDifference = Math.abs(source[0] - x);
        int minIndex = 0;
        for (int i = 1; i < source.length; i++) {
            long temp = Math.abs(source[i] - x);
            if (temp < minDifference) {
                minIndex = i;
                minDifference = temp;
            }
        }
        return source[minIndex];
    }

你可能感兴趣的:(java)