与阵列比较值,并得到最接近的值给它 [英] Compare value with array and get closest value to it

查看:223
本文介绍了与阵列比较值,并得到最接近的值给它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中的新秀,我努力学习该语言。

I'm a rookie in C# and I'm trying to learn that language.

你们能不能给我一个提示我怎么可以比较从中选择最低值的阵列?

Can you guys give me a tip how I can compare an array with a value picking the lowest from it?

这样的:

Double[] w = { 1000, 2000, 3000, 4000, 5000 };

double min = double.MaxValue;
double max = double.MinValue;

foreach (double value in w)
{
    if (value < min)
        min = value;
    if (value > max)
        max = value;
}

Console.WriteLine(" min:", min); 

给我的最低值w ,我怎么能现在比较?

如果我有:

int p = 1001 + 2000;  // 3001

我怎么能与阵列的列表现在比较,并找出了(3000)值是最接近的值我的Searchvalue?

how can I compare now with the list of the array and find out that the (3000) value is the nearest value to my "Searchvalue"?

推荐答案

您可以用一些简单的数学做到这一点,也有不同的做法。

You can do this with some simple mathematics and there are different approaches.

Double searchValue = ...;

Double nearest = w.Select(p => new { Value = p, Difference = Math.Abs(p - searchValue) })
                  .OrderBy(p => p.Difference)
                  .First().Value;

手动

Double[] w = { 1000, 2000, 3000, 4000, 5000 };

Double searchValue = 3001;
Double currentNearest = w[0];
Double currentDifference = Math.Abs(currentNearest - searchValue);

for (int i = 1; i < w.Length; i++)
{
    Double diff = Math.Abs(w[i] - searchValue);
    if (diff < currentDifference)
    {
        currentDifference = diff;
        currentNearest = w[i];
    }
}

这篇关于与阵列比较值,并得到最接近的值给它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆