本文介绍了将值与数组进行比较并获得最接近的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 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
的最低值,我现在如何比较?
gives me the lowest value of w
, how can I compare now?
如果我有:
int p = 1001 + 2000; // 3001
我现在如何与数组列表进行比较并找出 (3000) 值是最接近我的搜索值"的值?
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];
}
}
这篇关于将值与数组进行比较并获得最接近的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!