获取最接近数组中数字的值 [英] get closest value to a number in array
问题描述
我有一组正/负整数
int[] numbers = new int[10];
numbers[0] = 100;
numbers[1] = -34200;
numbers[2] = 3040;
numbers[3] = 400433;
numbers[4] = 500;
numbers[5] = -100;
numbers[6] = -200;
numbers[7] = 532;
numbers[8] = 6584;
numbers[9] = -945;
现在,我想针对这个数组测试另一个 int,并返回最接近 int 的数字.
Now, I would like to test another int against this array, and return the number that is closest to the int.
例如,如果我使用数字 490
,我会从数字 500
中取回第 4 项,这样做的最佳方法是什么?
For example if I used the number 490
i would get back item #4 from numbers 500
what is the best way to do something like this?
int myNumber = 490;
int distance = 0;
int idx = 0;
for(int c = 0; c < numbers.length; c++){
int cdistance = numbers[c] - myNumber;
if(cdistance < distance){
idx = c;
distance = cdistance;
}
}
int theNumber = numbers[idx];
那行不通.关于执行此操作的好方法有什么建议吗?
That doesn't work. Any suggestions on a good method to do this?
推荐答案
int myNumber = 490;
int distance = Math.abs(numbers[0] - myNumber);
int idx = 0;
for(int c = 1; c < numbers.length; c++){
int cdistance = Math.abs(numbers[c] - myNumber);
if(cdistance < distance){
idx = c;
distance = cdistance;
}
}
int theNumber = numbers[idx];
始终使用您正在考虑的第一个元素初始化您的最小/最大函数.使用诸如 Integer.MAX_VALUE代码>
或 Integer.MIN_VALUE
是一种获得答案的幼稚方式;如果您稍后更改数据类型(哎呀,MAX_LONG
和 MAX_INT
非常不同!)或者如果您将来想要编写泛型min/max
方法适用于 any 数据类型.
Always initialize your min/max functions with the first element you're considering. Using things like Integer.MAX_VALUE
or Integer.MIN_VALUE
is a naive way of getting your answer; it doesn't hold up well if you change datatypes later (whoops, MAX_LONG
and MAX_INT
are very different!) or if you, in the future, want to write a generic min/max
method for any datatype.
这篇关于获取最接近数组中数字的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!