2017-04-11 97 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'來編寫這些函數,那麼函數的輸出將取決於元素的順序。也就是說,您可以對數組進行洗牌並返回不同的值。你不會想這樣做。 –

相關問題