Compare value with array and get closest value to it(将值与数组进行比较并获得最接近的值)
问题描述
我是 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];
}
}
这篇关于将值与数组进行比较并获得最接近的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将值与数组进行比较并获得最接近的值


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01