Pascal 找到第二高的值

Pascal 找到第二高的值,pascal,Pascal,我编写这段代码是为了找出数组中第二高的值: var i, ZweitMax, Max : integer; begin Max := -maxint; ZweitMax := -maxint; for i := 1 to FELDGROESSE do if inFeld[i] > Max then begin ZweitMax := Max; Max := inFeld[i]; end else if inFeld[i] > ZweitMax then

我编写这段代码是为了找出数组中第二高的值:

var
 i,
 ZweitMax,
  Max : integer;

begin
Max := -maxint;
ZweitMax := -maxint;

for i := 1 to FELDGROESSE do


if inFeld[i] > Max then
  begin
  ZweitMax := Max;
  Max := inFeld[i];
  end
else
if inFeld[i] > ZweitMax then
begin
ZweitMax := inFeld[i];
FeldZweitMax := ZweitMax;
end
end; 
这段代码中的问题在哪里?为什么它没有打印出正确的值? 信息:代码是函数FeldZweitMax的一部分,当前有两个位置可以设置ZweitMax,但其中只有一个位置也会影响函数的返回代码FeldZweitMax

if
语句的第一部分可以更改为:

if inFeld[i] > Max then
begin
    ZweitMax := Max;
    FeldZweitMax := ZweitMax;  (* add this line *)
    Max := inFeld[i];
end
(* and so on *)
以确保正确更新返回值

或者,您可以在两个位置单独设置
ZweitMax
,然后在末尾设置返回值:

for i := 1 to FELDGROESSE do
begin
    if inFeld[i] > Max then
    begin
        ZweitMax := Max;
        Max := inFeld[i];
    end
    else
    begin
        if inFeld[i] > ZweitMax then
        begin
            ZweitMax := inFeld[i];
        end
    end
end;
FeldZweitMax := ZweitMax;
实际上我更喜欢后者,因为值的计算和返回是分开的。

目前有两个地方可以设置
ZweitMax
,但其中只有一个地方也会影响函数的返回代码,
FeldZweitMax

if
语句的第一部分可以更改为:

if inFeld[i] > Max then
begin
    ZweitMax := Max;
    FeldZweitMax := ZweitMax;  (* add this line *)
    Max := inFeld[i];
end
(* and so on *)
以确保正确更新返回值

或者,您可以在两个位置单独设置
ZweitMax
,然后在末尾设置返回值:

for i := 1 to FELDGROESSE do
begin
    if inFeld[i] > Max then
    begin
        ZweitMax := Max;
        Max := inFeld[i];
    end
    else
    begin
        if inFeld[i] > ZweitMax then
        begin
            ZweitMax := inFeld[i];
        end
    end
end;
FeldZweitMax := ZweitMax;

实际上我更喜欢后者,因为值的计算和返回是分开的。

Ok,这意味着我需要更改开始/结束?Ok,这意味着我需要更改开始/结束?