gpt4 book ai didi

c# - 将值与数组进行比较并获得最接近它的值

转载 作者:行者123 更新时间:2023-11-30 13:27:30 24 4
gpt4 key购买 nike

我是 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) 值是最接近我的“搜索值”的值?

最佳答案

你可以用一些简单的数学来做到这一点,而且有不同的方法。

林克

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];
}
}

关于c# - 将值与数组进行比较并获得最接近它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10894550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com