我是C#的新手,我正在努力学习这门语言。
你们能给我一个提示,我可以比较一个数组与从中选择最低值的数值吗?
喜欢:
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”的最接近的值?
答案 0 :(得分:13)
你可以用一些简单的数学来做到这一点,并且有不同的方法。
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];
}
}
答案 1 :(得分:1)
Double[] w = { 1000, 2000, 3000, 4000, 5000 };
var minimumValueFromArray = w.Min();
生成
正如预期的那样, 1000
导致我们执行Enumerable.Min。
同样适用于Enumerable.Max,以确定最大值:
Double[] w = { 1000, 2000, 3000, 4000, 5000 };
var maximumValueFromArray = w.Max();
考虑到您正在与double.MinValue
和double.MaxValue
进行比较,我假设您只想从数组中选择最小和最大的值。
如果这不是您要搜索的内容,请澄清。
答案 2 :(得分:0)
根据您的代码,您可以非常简单的方式实现这一目标
Double[] w = { 1000, 2000, 3000, 4000, 5000 }; // it has to be sorted
double search = 3001;
double lowerClosest = 0;
double upperClosest = 0;
for (int i = 1; i < w.Length; i++)
{
if (w[i] > search)
{
upperClosest = w[i];
break; // interrupts your foreach
}
}
for (int i = w.Length-1; i >=0; i--)
{
if (w[i] <= search)
{
lowerClosest = w[i];
break; // interrupts your foreach
}
}
Console.WriteLine(" lowerClosest:{0}", lowerClosest);
Console.WriteLine(" upperClosest:{0}", upperClosest);
if (upperClosest - search > search - lowerClosest)
Console.WriteLine(" Closest:{0}", lowerClosest);
else
Console.WriteLine(" Closest:{0}", upperClosest);
Console.ReadLine();
根据搜索值的位置,小于O(n)
答案 3 :(得分:-2)
Performance wise custom code will be more use full.
List<int> results;
int targetNumber = 0;
int nearestValue=0;
if (results.Any(ab => ab == targetNumber ))
{
nearestValue= results.FirstOrDefault<int>(i => i == targetNumber );
}
else
{
int greaterThanTarget = 0;
int lessThanTarget = 0;
if (results.Any(ab => ab > targetNumber ))
{
greaterThanTarget = results.Where<int>(i => i > targetNumber ).Min();
}
if (results.Any(ab => ab < targetNumber ))
{
lessThanTarget = results.Where<int>(i => i < targetNumber ).Max();
}
if (lessThanTarget == 0 )
{
nearestValue= greaterThanTarget;
}
else if (greaterThanTarget == 0)
{
nearestValue= lessThanTarget;
}
else if (targetNumber - lessThanTarget < greaterThanTarget - targetNumber )
{
nearestValue= lessThanTarget;
}
else
{
nearestValue= greaterThanTarget;
}
}