gpt4 book ai didi

java - 查找数组中最接近的数字

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:07 27 4
gpt4 key购买 nike

在一个数组中,首先我们必须找到一个想要的数字是否存在于其中?如果不是,那么我如何在 Java 中找到更接近给定所需数字的数字?

最佳答案

一个想法:

int nearest = -1;
int bestDistanceFoundYet = Integer.MAX_INTEGER;
// We iterate on the array...
for (int i = 0; i < array.length; i++) {
// if we found the desired number, we return it.
if (array[i] == desiredNumber) {
return array[i];
} else {
// else, we consider the difference between the desired number and the current number in the array.
int d = Math.abs(desiredNumber - array[i]);
if (d < bestDistanceFoundYet) {
// For the moment, this value is the nearest to the desired number...
bestDistanceFoundYet = d; // Assign new best distance...
nearest = array[i];
}
}
}
return nearest;

关于java - 查找数组中最接近的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/519881/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com