如何在数组中找到最小和最大的数字?

dna*_*naz 6 arrays delphi search delphi-2007

您好,我怎样才能在delphi中找到最小和最大的数字?

假设我有10个不同的数字存储在一个数组中:

如何在阵列中找到最大数量和最小数字?

Dav*_*nan 6

只需以线性方式循环遍历数组.保留最小值的变量和最大值的变量.初始化为数组中的第一个值.然后,对于每个元素,如果该元素分别小于或大于最小值或最大值,则更新最小值或最大值.

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;
Run Code Online (Sandbox Code Playgroud)

显然,此代码假定Count> 0.

请注意,您可以同样使用Math单元中的MinValue和MaxValue例程.

  • +1对于'MinValue`和`MaxValue`.还有[`MinIntValue`](http://docwiki.embarcadero.com/VCL/en/Math.MinIntValue)和[`MaxIntValue`](http://docwiki.embarcadero.com/VCL/en/Math. MaxIntValue). (3认同)