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];
}
}
这篇关于将值与数组进行比较并获得最接近的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将值与数组进行比较并获得最接近的值
基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
