使用java查找数组中给定数字的最接近的最大数字

时间:2017-02-10 12:56:55

标签: java

float[] array={a,b,c,d};
float distance = Math.abs(array[0] - givennumber);
int idx = 0;

for(int c = 1; c < array.length; c++) {
    float cdistance = Math.abs(array[c] - givennumber);
    if (cdistance < distance) {
        idx = c;
        distance = cdistance;
        nearestlargest=array[idx];
    }
}
return nearestlargest;

这是我到目前为止为找到给定数字的最接近的大数而尝试的,但是我得到阵列中所有数字中最大的数字,请帮助解决这个问题。

1 个答案:

答案 0 :(得分:1)

如果对于{1, 2, 3, 5, 10, 100}givennumber = 9,您的算法应该返回10,它可以正常工作。

但我发现Math.abs()存在不同的问题。如果您有{1, 2, 3, 10, 100}givenNumber=5(3, 5) = 2(10, 5)=5的距离。但我想结果你需要10而不是3

例如,您的算法可能如下所示:

    float distance = Float.MAX_VALUE; //use max distance as initial value to compare
    int idx = -1; // use -1 instead of 0, because array can be without nearest largest (101 for example above)
    for(int c = 0; c < array.length; c++) {
        float cdistance = array[c] - givennumber; // calculate a distance
        if (cdistance > 0 && distance > cdistance) { // we are interesting just in positive distances for largest numbers
            distance = cdistance;
            idx = c;
        }
    }

    if (idx < 0) {
        return Float.NaN; //return NaN if array doesn't contain a nearest largest (you can use Float.isNaN() to check result of function)
    } else {
        return array[idx]; //return nearest largest
    }