找到第二高的值
Find the second highest value
我写了这段代码来找出数组中第二大的值:
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
,但只有一个处也影响了return 函数代码,FeldZweitMax
.
if
语句的第一部分可以改成:
if inFeld[i] > Max then
begin
ZweitMax := Max;
FeldZweitMax := ZweitMax; (* add this line *)
Max := inFeld[i];
end
(* and so on *)
以确保正确更新 return 值。
或者,您可以只在两个地方单独设置 ZweitMax
,然后在最后设置 return 值:
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;
实际上我更喜欢后者,因为值的计算和 return 是不同的事情。
我写了这段代码来找出数组中第二大的值:
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
,但只有一个处也影响了return 函数代码,FeldZweitMax
.
if
语句的第一部分可以改成:
if inFeld[i] > Max then
begin
ZweitMax := Max;
FeldZweitMax := ZweitMax; (* add this line *)
Max := inFeld[i];
end
(* and so on *)
以确保正确更新 return 值。
或者,您可以只在两个地方单独设置 ZweitMax
,然后在最后设置 return 值:
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;
实际上我更喜欢后者,因为值的计算和 return 是不同的事情。