你好,我该如何在Delphi中找出最大值和最小值?
假设有10个不同的数字存储在一个数组中:
如何找到数组中的最大值和最小值?
你好,我该如何在Delphi中找出最大值和最小值?
假设有10个不同的数字存储在一个数组中:
如何找到数组中的最大值和最小值?
只需要按线性方式循环遍历数组。保持一个变量用于存储最小值,另一个变量用于存储最大值。将这两个变量都初始化为数组中的第一个值。然后,对于每个元素,如果该元素小于最小值或大于最大值,则更新最小值或最大值。
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。
请注意,您也可以使用Math单元中的MinValue和MaxValue例程。
遍历数组并与之前找到的最小值和最大值进行比较。
这里是一段代码片段。根据您的澄清,我已编辑代码以使用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;
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.
MinValue
å’ŒMaxValue
。还有MinIntValue
å’ŒMaxIntValue
。 - NGLN