找到第二高的值

时间:2016-11-09 12:56:27

标签: 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
begin
ZweitMax := inFeld[i];
FeldZweitMax := ZweitMax;
end
end; 

本规范中的问题在哪里?为什么它不能打印出正确的值? 信息:该代码是函数FeldZweitMax

的一部分

1 个答案:

答案 0 :(得分:2)

目前有两个位置设置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;

我实际上更喜欢后者,因为计算和返回值是不同的事情。

相关问题