得到最接近的值,以在阵列的数 [英] get closest value to a number in array
问题描述
我有正/负整数数组
INT []号= INT新[10];
号码[0] = 100;
号[1] = -34200;
号码[2] = 3040;
数[3] = 400433;
数[4] = 500;
数[5] = -100;
号[6] = -200;
数[7] = 532;
数[8] = 6584;
数[9] = -945;
现在,我想测试的此阵另一int和返回最接近的int数。
例如,如果我用了数 490
我会再项目#4从数字 500
什么是做这样的事情最好的办法?
INT mynumber的= 490;
INT距离= 0;
INT IDX = 0;
对于(INT C = 0;℃下numbers.length; C ++){
INT cdistance =号[C] - mynumber的;
如果(cdistance<距离){
IDX = C;
距离= cdistance;
}
}
INT数量写=号[IDX];
这是行不通的。一个好方法有什么建议这样做?
INT mynumber的= 490;
INT距离= Math.abs(号码[0] - mynumber的);
INT IDX = 0;
对于(INT C = 1;℃下numbers.length; C ++){
INT cdistance = Math.abs(编号[C] - mynumber的);
如果(cdistance<距离){
IDX = C;
距离= cdistance;
}
}
INT数量写=号[IDX];
总是与你正在考虑的第一要素初始化最小/最大功能。使用像<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#MAX_VALUE\"><$c$c>Integer.MAX_VALUE$c$c>或<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#MIN_VALUE\"><$c$c>Integer.MIN_VALUE$c$c>是让你回答一个天真的方式;它不保持良好,如果你更改后的数据类型(哎呦, MAX_LONG
和 MAX_INT
有很大的不同!)或如果,在未来,要编写一个通用的最小/最大
方法的任何的数据类型。
I have an array of positive/negative ints
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;
Now, I would like to test another int against this array, and return the number that is closest to the int.
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];
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屋!