这个是考虑优先级的算法,乘法和除法优先级比加法和减法高。
unit Unit1;
interface
uses
Windows,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
bStop : Boolean;
public
{ Public declarations }
function Calc(m,n :do
uble;
s : Integer) :do
uble;
procedure IsOK(i1,i2,i3,i4,s1,s2,s3 : Integer);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
I1,i2,i3,i4 : Integer;
s1,s2,s3 : Integer;
begin
bStop := False;;
for I1 := 1 to 99do
begin
for s1 := 1 to 4do
begin
for i2 := 1 to 99do
begin
for s2 := 1 to 4do
begin
for i3 := 1 to 99do
begin
for s3 :=1 to 4do
begin
for i4 := 1 to 99do
begin
if bStop then
Exit;
IsOK(i1,i2,i3,i4,s1,s2,s3);
Application.ProcessMessages;
end;
end;
end;
end;
end;
end
end;
end;
function TForm1.Calc(m,n :do
uble;
s : Integer) :do
uble;
begin
result := 0;
case s of
1 : Result := m + n;
2 : Result := m - n;
3 : Result := m * n;
4 : Result := m / n;
end;
end;
procedure TForm1.IsOK(i1, i2, i3, i4, s1, s2, s3: Integer);
var
r :do
uble;
S : String;
L : Integer;
begin
L := (s1 + s1 mod 2) div 2 * 100 + (s2 + s2 mod 2) div 2 * 10 + (s3 + s3 mod 2) div 2;
case L of
111,211,221,222 : begin
R := Calc(i1,i2,s1);
R := Calc(R,i3,s2);
R := Calc(R,i4,s3);
end;
112,212 : begin
R := Calc(Calc(i1,i2,s1),Calc(i3,i4,s3),s2);
end;
121 : begin
R := Calc(i2,i3 ,s2);
R := Calc(R ,i1 ,s1);
R := Calc(R ,i4 ,s3);
end;
122 : begin
R := Calc(i2,i3 ,s2);
R := Calc(R ,i4 ,s3);
R := Calc(R ,i1 ,s1);
end;
else
Memo1.Lines.Append('不可能(' + IntToStr(L) + ')');
R := 1;
end;
if (1 <> R ) then
Exit;
S := '+-*/';
Memo1.Lines.Append(IntToStr(i1) + S[s1] + IntToStr(i2) + S[s2] + IntToStr(i3) + S[s3] + IntToStr(i4));
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
bStop := True;
end;
end.