How do I find the closest array element to an arbitrary (non-member) number?

前端 未结 5 1500
闹比i
闹比i 2021-01-18 13:48

Seemingly similar questions: \"Finding closest number in an array\" (in Java) and \"find nearest match to array of doubles\" (actually a geography problem).

5条回答
  •  自闭症患者
    2021-01-18 14:41

    Something like this:

    double[] values = new double[]
    {
        1.8,
        2.4,
        2.7,
        3.1,
        4.5
    };
    
    double difference = double.PositiveInfinity;
    int index = -1;
    
    double input = 2.5;
    
    for (int i = 0; i < values.Length; i++)
    {
        double currentDifference = Math.Abs(values[i] - input);
    
        if (currentDifference < difference)
        {
            difference = currentDifference;
            index = i;
        }
    
        // Stop searching when we've encountered a value larger
        // than the inpt because the values array is sorted.
        if (values[i] > input)
            break;
    }
    
    Console.WriteLine("Found index: {0} value {1}", index, values[index]);
    

提交回复
热议问题