2016-11-07 62 views
0

我有問題顯示第二大值。如何找到Pascal的第二大值

這裏是代碼

program testeFeldZweitMax (input, output); 
{ testet die Funktion FeldZweitMax } 

const 
    FELDGROESSE = 10; 

type 
    tIndex = 1..FELDGROESSE; 
    tFeld = array [tIndex] of integer; 

var 
    Feld : tFeld; 
    i : integer; 

function FeldZweitMax (var inFeld : tFeld) : integer; 
var 
    Maximum: integer; 
    j : tIndex; 
begin 
    Maximum := inFeld[1]; 
    for j := 2 to FELDGROESSE do 
    if inFeld[j] > Maximum then 
     Maximum := inFeld[j]; 
    FeldZweitMax := Maximum 
end; 

begin { Testprogramm } 
    writeln('Bitte geben Sie ', FELDGROESSE, ' Zahlen ein:'); 
    for i := 1 to FELDGROESSE do 
    read (Feld [i]); 
    writeln('Die zweitgroesste Zahl ist ', FeldZweitMax (Feld), '.'); 
end. { testeFeldZweitMax } 

正如你可以看到代碼顯示我的只有最大的價值。我需要一些幫助來顯示第二大價值。

var 
    Maximum, ZweitMax: integer; 
    j : tIndex; 
begin 
    Maximum := inFeld[1]; 
    ZweitMax := inFeld[2]; 
    for j := 1 to FELDGROESSE do 
    begin 
    if inFeld[j] < Maximum then 
     inFeld[j] := Maximum; 
    Maximum := ZweitMax; 
    ZweitMax := inFeld[j]; 
    FeldZweitMax := ZweitMax 
    end 
end; 

它不能正常工作。對我有些建議?

+0

您總是將feldzweitmax等同於最大值。這合乎邏輯嗎?然後它總是一樣的。關鍵是找到about/when/Maximum包含您想要的值並將if擴展爲開始結束塊。 –

+0

@MarcovandeVoort是的,我知道,在這種情況下,我總是等於最大值。這就是爲什麼我需要幫助。在您開始前* – Marco

回答

3

考慮你(有些時候)值Maximum > ZweitMax(分別是f.ex. 5和2)。 的下一個值(x)的評估可能是

  • 一個)X>最大
  • b)中X> ZweitMax(但小於最大)
  • c)中X < ZweitMax

在情況下a)最大值應該變爲x並且ZweitMax應該變成前值最大值

在情況b)最大值應該保持並且ZweitMax應該變爲x

在情況c)至最長和ZweitMax(IOW,不需要採取行動)

一對夫婦的提示沒有變化:

  • 初始化最大和ZweitMax到儘可能小的值(根據類型),然後開始評估實際輸入值。

  • 如果a)在將新值分配給最大值之前將ZweitMax設置爲先前的最大值。

+0

* ..和最大ZweitMax + 1。*。如果所有輸入值都處於最低水平呢? –

+1

@LURD好點!其實這兩個值應該是最小的。感謝您的支持。 –

+0

榮譽解釋的邏輯,而不是隻寫代碼。如果我能提供一個,那將值得第二個贊成。 –