【发布时间】:2011-10-31 01:10:30
【问题描述】:
你好,我怎样才能在delphi中找到最小和最大的数字?
假设我有 10 个不同的数字存储在一个数组中:
如何找到数组中的最大数和最小数?
【问题讨论】:
标签: arrays delphi search delphi-2007
你好,我怎样才能在delphi中找到最小和最大的数字?
假设我有 10 个不同的数字存储在一个数组中:
如何找到数组中的最大数和最小数?
【问题讨论】:
标签: arrays delphi search delphi-2007
只需以线性方式循环遍历数组。为最小值保留一个变量,为最大值保留一个变量。将两者都初始化为数组中的第一个值。然后对于每个元素,如果该元素分别小于或大于最小值或最大值,则更新最小值或最大值。
minval := a[0];
maxval := a[0];
for i := 1 to Count-1 do
begin
if a[i]<minval then
minval := a[i]
else if a[i]>maxval then
maxval := a[i];
end;
显然,这段代码假定 Count>0。
请注意,您同样可以使用数学单元中的 MinValue 和 MaxValue 例程。
【讨论】:
MinValue 和MaxValue。还有MinIntValue和MaxIntValue。
遍历数组并与之前找到的最小值和最大值进行比较。
这是一个代码 sn-p。根据您的说明,我已编辑代码以使用 Int64。
Min := High(Int64);
Max := Low(Int64);
for ThisNumber in MyArray do
begin
if ThisNumber < Min then
begin
Min := ThisNumber;
end
if ThisNumber > Max then
begin
Max := ThisNumber;
end;
end;
有趣的是,Math.pas 中的 MaxIntValue 实现为:
function MaxIntValue(const Data: array of Integer): Integer;
var
I: Integer;
begin
Result := Data[Low(Data)];
for I := Low(Data) + 1 to High(Data) do
if Result < Data[I] then
Result := Data[I];
end;
这个实现,类似于大卫的回答,使用第一个数组值作为初始值。这假设数组至少有一个元素。另请注意,循环可以从 Low(Data) + 1 开始并保存一个不必要的比较。对于您描述的数据,每个数组中有 100 个元素,您最多可以提高 1% 的速度。
如果性能无关紧要,那么 MinIntValue 和 MaxIntValue 会更简洁。如果您自己滚动,那么您只需遍历数组一次而不是两次。
【讨论】:
Create a function that takes an array of numbers and return both the minimum and maximum numbers, in that order.
// Examples
// minMax([1, 2, 3, 4, 5]) ➞ [1, 5]
// minMax([2334454, 5]) ➞ [5, 2334454]
// minMax([1]) ➞ [1, 1]
const minMax = (arr) => {
let newMinMax = [];
let min = Math.min(...arr);
newMinMax.push(min);
let max = Math.max(...arr);
newMinMax.push(max);
return newMinMax;
};
// console.log(minMax([1, 2, 3, 4, 5]));
// console.log(minMax([2334454, 5]));
// console.log(minMax([1]));
Used javascript build in functions for that .Math.min function requires distinct number but when we provide array it will give you a NaN to avoid that use [...arr]
spread operator of Math.min.apply(Math,arr) function.
【讨论】: