get closest value to a number in array

后端 未结 12 1817
庸人自扰
庸人自扰 2020-12-01 07:52

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         


        
12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 08:23

    cdistance = numbers[c] - myNumber. You're not taking the absolute value of the difference. If myNumber is a lot greater than numbers[c] or if numbers[c] is negative, the comparison will register as the "minimum difference".

    Take for example the case where numbers[c] = -34200. numbers[c] - myNumber would then be -34690, a lot less than the distance.

    Also, you should initialize distance to a large value, as no solution has been found at the start.

提交回复
热议问题