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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…