只是提供一种思路,要把运算顺序考虑进去也简单:
unit Unit7;
interface
uses
Windows, Messages, SysUtils, StrUtils,Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm7 = class(TForm)
Button1: TButton;
Label1: TLabel;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
Function Calc(x1,x2,x3,x4:Integer;oper1,oper2,oper3:char;operseq:integer):double;overload;
end;
var
Form7: TForm7;
oper:array[0..3] of char =('+','-','x','/');
implementation
{$R *.dfm}
procedure TForm7.Button1Click(Sender: TObject);
var
i,j,k,l,n1,n2,n3,operseq,count:Integer;
exp:string;
v:double;
begin
count:=0 ;
for i := 1 to 10 do
for j := 1 to 10 do
for k := 1 to 10 do
for l := 1 to 10 do
for n1 := 0 to 3 do
for n2 := 0 to 3 do
for n3 := 0 to 3 do
for operseq := 0 to 3 do
begin
v:=Calc(i,j,k,l,oper[n1],oper[n2],oper[n3],operseq);
if (v>=24) and (v<24.00000001) then
begin
case operseq of
0:exp:='(('+inttostr(i)+oper[n1]+inttostr(j)+')'+oper[n2]+inttostr(k)+')'+oper[n3]+inttostr(l);
1:exp:='('+inttostr(i)+oper[n1]+inttostr(j)+')'+oper[n2]+'('+inttostr(k)+oper[n3]+inttostr(l)+')';
2:exp:=inttostr(i)+oper[n1]+'(('+inttostr(j)+oper[n2]+inttostr(k)+')'+oper[n3]+inttostr(l)+')';
3:exp:='('+inttostr(i)+oper[n1]+'('+inttostr(j)+oper[n2]+inttostr(k)+'))'+oper[n3]+inttostr(l);
end;
inc(count);
memo1.Lines.Add(exp+'=24') ;
Label1.Caption:=inttostr(count);
end;
end;
end;
//假设运算符是#
//operseq=0 ((i#j)#k)#l
//operseq=1 (i#j)#(k#l)
//operseq=2 i#((j#k)#l)
//operseq=3 (i#(j#k))#l
function TForm7.Calc(x1,x2,x3,x4:Integer;oper1,oper2,oper3:char;operseq:integer):double;
var
v,vv:double;
begin
try //捕获除数为0的情况
case operseq of
0: //operseq=0 ((i#j)#k)#l
begin
case oper1 of
'+':v:=x1+x2;
'-':v:=x1-x2;
'x':v:=x1*x2;
'/':v:=x1/x2;
end;
case oper2 of
'+':v:=v+x3;
'-':v:=v-x3;
'x':v:=v*x3;
'/':v:=v/x3;
end;
case oper3 of
'+':v:=v+x4;
'-':v:=v-x4;
'x':v:=v*x4;
'/':v:=v/x4;
end;
result:=v;
end;
1: //operseq=0 (i#j)#(k#l)
begin
case oper1 of
'+':v:=x1+x2;
'-':v:=x1-x2;
'x':v:=x1*x2;
'/':v:=x1/x2;
end;
case oper3 of
'+':vv:=x3+x4;
'-':vv:=x3-x4;
'x':vv:=x3*x4;
'/':vv:=x3/x4;
end;
case oper2 of
'+':v:=v+vv;
'-':v:=v-vv;
'x':v:=v*vv;
'/':v:=v/vv;
end;
result:=v;
end;
2: //operseq=2 i#((j#k)#l)
begin
case oper2 of
'+':v:=x2+x3;
'-':v:=x2-x3;
'x':v:=x2*x3;
'/':v:=x2/x3;
end;
case oper3 of
'+':v:=v+x4;
'-':v:=v-x4;
'x':v:=v*x4;
'/':v:=v/x4;
end;
case oper1 of
'+':v:=x1+v;
'-':v:=x1-v;
'x':v:=x1*v;
'/':v:=x1/v;
end;
result:=v;
end;
3: //operseq=3 (i#(j#k))#l
begin
case oper2 of
'+':v:=x2+x3;
'-':v:=x2-x3;
'x':v:=x2*x3;
'/':v:=x2/x3;
end;
case oper1 of
'+':v:=x1+v;
'-':v:=x1-v;
'x':v:=x1*v;
'/':v:=x1/v;
end;
case oper3 of
'+':v:=v+x4;
'-':v:=v-x4;
'x':v:=v*x4;
'/':v:=v/x4;
end;
result:=v;
end;
end
except on E: Exception do result:=-1;
end;
end;
end.