计算出哪两个数字更接近另一个数字Java

时间:2016-02-23 00:02:21

标签: java math

我正在试图找出一种方法来计算出两个数字中哪一个更接近另一个数字让我们说我们有一个a,b,c

a = 0.7 b = 1.8且c = 1;

如何在Java中找出a或b中的哪个数字更接近c。

5 个答案:

答案 0 :(得分:2)

你可以通过coll MyF( a , b , c )

使用这个函数来实现
String MyF(double a , double b , double c )
    {
     if (Math.abs(c - a) < Math.abs(c - b)) 
         return a;
     else
        return b;
   }

答案 1 :(得分:0)

你可以这样做:

double a = 0.7;
double b = 1.8;
double c = 1;

// Compare the absolute values of the differences
double closer = Math.abs(c - a) < Math.abs(c - b) ? a : b;
System.out.println(closer);

// 0.7

答案 2 :(得分:0)

您可以比较差异绝对值的最小值(在您的情况下为0.3和0.8)。

if (Math.abs(a-c) <= Math.abs(b-c)) {
  System.out.println("A is closer");
} else {
  System.out.println("B is closer");
}

请注意,0.3和1.8必须为float / double,而不是int

答案 3 :(得分:0)

只是为了提供一个更通用的解决方案,如果你想要一个 Comparator可以比较数字与另一个数字的接近程度,那么它看起来像这样:

Comparator<Double> closenessToC = Comparator.comparingDouble(n -> Math.abs(c - n));

这适用于任何一组数字(而不仅仅是两组):

Stream.of(4.5, 8.9, -11.2).min(closenessToC).ifPresent(System.out::println);

答案 4 :(得分:0)

您是如何呈现数据的?它总是3个数字吗?它是一个阵列吗?解决方案将根据您的输入数量是否固定而有很大差异。

写下以下内容,找到数字数组中最接近的2个数字。

public class Test {

    static double[] findClosest(double[] dblArray) {
        double[] closest = new double[2];

        //int diff will keep track of the best of the differences
        //between the numbers we are compairing. Need to start off at 
        //largest number possible.
        double bestDiff = Double.MAX_VALUE;

        //currDiff will calculate the current difference in doubles
        double currDiff;

        //You want to iterate through every value you have
        for (int i = 0; i < dblArray.length; i++) {
            for (int j = 0; j < dblArray.length; j++) {
                if (i != j) { //You don't want it to compare to itself.
                    //System.out.println("Subtracting: " + dblArray[i] + " - " + dblArray[j]);
                    currDiff = Math.abs(dblArray[i] - dblArray[j]);
                    if (currDiff < bestDiff) {
                        closest[0] = dblArray[i];
                        closest[1] = dblArray[j];
                        bestDiff = currDiff;
                       // System.out.println("Setting closest:" + dblArray[i] + ", " + dblArray[j] + ", bestDiff: " + bestDiff);
                    }
                }
            }
        }

        return closest;
    }

    public static void main(String[] args) {
        double[] testArray = new double[]{.7, 1.8, 1};
        double[] resultArray = findClosest(testArray);
        System.out.println("Closest were: " + resultArray[0] + ", " + resultArray[1]);
    }
}

运行这个你得到:

run:
Closest were: 0.7, 1.0
BUILD SUCCESSFUL (total time: 0 seconds)

我知道仅仅为2个值返回数组并不是最实用的,我可以返回一个字符串,但重点是证明逻辑。我还意识到您要求abc进行比较。您可以使用我上面编写的代码中的逻辑并稍微调整一下来实现它。