【问题标题】:how do i check to see if a double array contains a certain double in c#我如何检查一个双精度数组是否包含 C# 中的某个双精度
【发布时间】:2020-07-22 05:26:01
【问题描述】:

我现在正在使用此代码

        double[] LocationsDown = { 40, 85, 130, 175, 220, 265, 310, 355 };
        double[] LocationsUp = { 50, 95, 140, 185, 230, 275, 320, 5 };
        double curretangle = Math.Round(targetAngle);

        if (LocationsDown == curretangle) // <- Compile Time Error here
        {
            //thing
        }

但它说

" 运算符 '==' 不能应用于 'double[]' 类型的操作数和 '双' "

我不明白检查数组是否包含所述双精度的正确方法我觉得这将是一个简单的解决方法,我只是无法将手指放在上面。

【问题讨论】:

  • 通常在使用 floating point 时,我们会比较 tolerance,例如bool contains = LocationsDown.Any(item =&gt; Math.Abs(item - valueToFind) &lt; tolerance);

标签: c# double


【解决方案1】:

一般情况中,我们必须将double 的值与一些tolerance 进行比较:

 if (Math.Abs(someValue - valueToCheck) <= tolerance) {...}

当使用 collections 时,我们可以使用 Linq 来查询它们:

 using System.Linq;

 ...

 double tolerance = 1e-6; 

 bool contains = LocationsDown.Any(item => Math.Abs(item - curretangle) <= tolerance);

【讨论】:

  • 感谢您回答我的问题,我确信使用此方法有一些好处,但由于它更易于使用 .contains 并且它仅适用于太空工程师脚本,我认为它也不重要非常感谢你。
【解决方案2】:

使用.Contains:

if (LocationsDown.Contains(curretangle))

【讨论】:

    猜你喜欢
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2020-06-02
    相关资源
    最近更新 更多