在float列表中找到最近的数字

时间:2015-10-14 14:45:52

标签: c# arrays find

嗨,我有一个浮动列表

       List<float> distance = new List<float>();
        distance.Add(66.2F);
        distance.Add(69.9F);
        distance.Add(70.2F);
        distance.Add(70.3F);
        distance.Add(70.6F);
        distance.Add(71.4F);
        distance.Add(71.6F);

我有一个扩展方法,它从这个数组中得到最接近的数字

 public static class extenstions
{
    public static float ClosestTo(this IEnumerable<float> collection, float target)
    {

        var closest = float.MaxValue;
        var minDifference = float.MaxValue;
        foreach (var element in collection)
        {
            var difference = Math.Abs((long)element - target);
            if (minDifference > difference)
            {
                minDifference = (int)difference;
                closest = element;
            }
        }

        return closest;
    }
}

float nearest = distance.ClosestTo(70F); 现在,如果我想找到最接近的数字70,它将返回70.2我想要的是修改此函数以返回较小的最接近的69.9而不是更高的值70.2。 你能帮忙吗?

3 个答案:

答案 0 :(得分:3)

使用Linq:

public static float ClosestTo(this IEnumerable<float> collection, float target)
{
    return collection.OrderBy(x => Math.Abs(target - x)).First();
}

或者,使用MinBy中的Linq.Extras扩展方法:

public static float ClosestTo(this IEnumerable<float> collection, float target)
{
    return collection.MinBy(x => Math.Abs(target - x));
}

比使用OrderBy更好,因为它在O(n)而不是O(n log n)中运行。

编辑:如果两个数字同样接近目标而你想要两者中的较大者,你可以这样做:

public static float ClosestTo(this IEnumerable<float> collection, float target)
{
    return collection
        .OrderBy(x => Math.Abs(target - x))
        .ThenByDescending(x => x)
        .First();
}

答案 1 :(得分:2)

可能当你在昏迷70,2之后将你的价值转移到长期失去的数字时 - &gt; 70和69,9 - &gt; 69和70最接近70而不是69

如果你想从左或右接近,请使用:

window.onload = function () {

    var tablerow = document.body.getElementsByTagName('tr');
    console.log(tablerow);

     // Convert the HTMLCollection into a true javascript Array, so we can do "stuff" with it       
    var tablerowArr = Array.prototype.slice.call(tablerow);
    console.log(tablerowArr);

// Do stuff
    tablerowArr.forEach(function (value, i) {
        console.log(i, value);

        tablerow[i].onclick = function (e) {
            //console.log("clicked!");


            var newArr = tablerowArr.slice(i, i + 1);
            //console.log(tablerow);
            console.log(i);
            //console.log(tablerowArr);
            console.log('newArr', newArr);


            tablerowArr.forEach(function (value, i) {

                // first reset all instances of data-XXX  
                tablerowArr[i].setAttribute('data-display', "collapsed");
               // tablerowArr[i].setAttribute('data-state', "enabled");

                // Set the <tr> data-display attribute to expanded/collapsed on click
                newArr[0].setAttribute('data-display', tablerowArr[i].getAttribute('data-display') === "collapsed" ? "expanded" : "collapsed");
                //tablerowArr[i].setAttribute('data-display', tablerowArr[i].getAttribute('data-display') === "collapsed" ? "expanded" : "collapsed");

                // Set the <tr> data-state attribute to enabled/disabled on click
                newArr[0].setAttribute('data-state', newArr[0].getAttribute('data-state') === "disabled" ? "enabled" : "enabled");
                tablerowArr[i].setAttribute('data-state', newArr[0].getAttribute('data-state') === "enabled" ? "disabled" : "enabled");

            });

            e.preventDefault();
        };
    });
};

其中WebServer(ISS)->WebServer->Application Development add .NET Extensibility 3.5 add .NET Extensibility 4.5 add ASP.NET 4.5 add ISAPI Extensions add ISAPI Filters 是正确的,public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a word to check: "); String checkWord = sc.nextLine(); System.out.println(isPalindrome(checkWord)); sc.close(); } public static boolean isPalindrome(String str) { StringBuilder secondSB = new StringBuilder(); StringBuilder sb = new StringBuilder(); sb.append(str); for(int i = 0; i<sb.length();i++){ char c = sb.charAt(i); if(Character.isUpperCase(c)){ sb.setCharAt(i, Character.toLowerCase(c)); } } secondSB.append(sb); return sb.toString().equals(secondSB.reverse().toString()); } 是左(如果您想将 public static float ClosestTo(this IEnumerable<float> collection, float target) { float a = collection.Where(x => x >= target).OrderBy(x => x - target).First(); float b = collection.Where(x => x < target).OrderBy(x => Math.Abs(target - x)).First(); return a.Equals(b) ? a : Math.Min(a, b); } 更改为a

答案 2 :(得分:1)

不要将元素变量强制转换为long。