在数组中查找最小元素时,如何指定自定义代码进行比较?
例如,我有两个数组:
int[] a = new int[] {3, 6, 8};
int[] b = new int[] {9, -2, 5};
我想弄清楚,元素与相应索引的最小比率是多少(即找到 3/9
、6/(-2)
的最小值和 8/5
),然后返回索引。我已经知道 Array.Min(),但我想知道是否可以对其进行任何类型的定制。
最佳答案
也许是这样的:
double smallest = double.MaxValue;
int smallestIndex = 0;
for (int i = 0; i < (a.Length > b.Length ? b.Length : a.Length); i++)
{
if ((double)a[i] / b[i] < smallest)
{
smallest = (double)a[i] / b[i];
smallestIndex = i;
}
}
smallestIndex 将包含末尾最小比率的索引。
关于.net - C# 数组 : finding custom minimal element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1807848/