2017-04-11 314 views
1

在Delphi 6中是否有内置函数?即,检索MaxValue函数返回值的索引的函数。如何找到数组中最大值的索引?

如果不是什么是最有效的例程?

+0

什么数据类型的数组? –

+0

@GerryColl'MaxValue'对浮点数据数组进行操作 –

回答

1

德尔福没有提供这样的功能,不在Delphi 6中,除非我错了,甚至在现代的Delphi版本中都没有。

没有关于数组内容的任何信息,您必须检查每个元素以查找最大值以及相应的索引。

uses 
    Math; // MaxDouble is defined by this unit 

function IndexOfMaxValue(const x: array of Double): Integer; 
var 
    Index: Integer; 
    MaxValue: Double; 
begin 
    Result := -1; 
    MaxValue := -MaxDouble; 
    for Index := 0 to high(x) do begin 
    if x[Index]>MaxValue then begin 
     Result := Index; 
     MaxValue := x[Index]; 
    end; 
    end; 
end; 

注意,在并列的情况下,即与所述最大值超过一个元件,该函数将返回第一个这样的元素的索引。

正如@LURD指出的那样,如果数组中的所有元素都是-MaxDouble那么函数返回-1。这可以这样解决:

function IndexOfMaxValue(const x: array of Double): Integer; 
var 
    Index: Integer; 
    MaxValue: Double; 
begin 
    if high(x) = -1 then begin 
    Result := -1; 
    end else begin 
    Result := 0; 
    MaxValue := x[0]; 
    for Index := 1 to high(x) do begin 
     if x[Index]>MaxValue then begin 
     Result := Index; 
     MaxValue := x[Index]; 
     end; 
    end; 
    end; 
end; 
+0

ok这就是我所做的。那么 – bbd

+0

在比较双精度时,我总是更喜欢使用CompareValue(如果在Delphi 6中可用)比较运算符。 –

+0

@SebastianProske我不会。在这种情况下使用绝对是错误的,因为'MaxValue'使用了比较运算符。我怀疑你的评论是基于对浮点运算的模糊评估。例如,如果您使用'CompareValue'来编写这些函数,那么函数的输出将取决于元素的顺序。也就是说,您可以对数组进行洗牌并返回不同的值。你不会想这样做。 –

相关问题