【发布时间】:2016-04-06 13:11:34
【问题描述】:
我有一个Edit1,您可以在其中输入像2 20 10 -3 这样的数字,当您单击Button1 时,它会显示最大和最小数字 max = 20 min = -3。
尝试这样做时,当我拿出数字时,它会在 Edit1 中交换 min 和 max 数字,就像 2 -3 10 20 一样,我以我的方式尝试了它,但其他输入的数字改变了位置。
我尝试了很多方法:
Edit4.Text:= (inttostr(min)+' '+ inttostr(max));
但它会覆盖其他数字。
然后我尝试使用
maxnumb := Edit4
Edit4.Text := StringReplace(maxnumb, inttostr(max), inttostr(min),
[rfReplaceAll, rfIgnoreCase]);
Edit1.Text := StringReplace(maxnumb, inttostr(min), inttostr(max),
[rfReplaceAll, rfIgnoreCase]);
但它只交换了第一个数字,当我再次单击Button1 时,它交换了第二个数字。
没有尝试交换的代码:
procedure TForm1.Button1Click(Sender: TObject);
var
oSL: TStringlist;
s, ss: string;
a: array [1 .. 15] of integer;
i, j, k, p, code: integer;
max, min: integer;
before, after: string;
begin
s := Edit1.Text;
s := concat(s, #32);
i := 0;
while Length(s) > 0 do
begin
i := i + 1;
p := pos(#32, s);
ss := copy(s, 1, p - 1);
Val(ss, k, code);
a[i] := k;
delete(s, 1, p);
end;
// Max
max := a[1];
For j := 1 to i do
if max < a[j] then
max := a[j];
// Min
min := a[1];
For j := 1 to i do
if min > a[j] then
min := a[j];
// Put out Max/Min
Edit3.Text := IntToStr(max);
Edit2.Text := IntToStr(min);
end;
【问题讨论】:
-
请edit你的问题,不清楚:交换
2 20 10 -3中的最小值和最大值不会返回2 -3 20 10而是2 -3 10 20。 -
为了解决这个问题,请停止您的 StringReplace 尝试。只需解析 Edit.Text 中的所有数字,对整数数组进行处理,然后将它们全部连接回 Edit.text
-
maxnumb 是什么类型?如果它是一个字符串,那么第一行 "maxnumb := edit4" 将不会编译。如果它是一个 Editbox,那么 stringreplace 将不会编译。请检查您的问题中是否包含正确的代码
-
是的,maxnumb 是一个字符串,我会尝试在没有字符串替换的情况下做一些事情。
-
现在我得到一个错误 unit1.pas(72,23) 错误:为调用“CompareReal”
function CompareReal(List: TStringList; Index1, Index2: Integer): Integer; begin // make use of the comparer in unit Math Result := CompareValue(StrToFloat(List[Index1]), StrToFloat(List[Index2])); end;指定的参数数量错误@