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;
这是我到目前为止为找到给定数字的最接近的大数而尝试的,但是我得到阵列中所有数字中最大的数字,请帮助解决这个问题。
答案 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
}