我写过一个,但没有考虑括号..你可以自己处理一下.
function getNum(str:string):string;
var
stra,strb,F:string;
ipos1,ipos2,ipos3,ipos4:integer;
valuea,valueb:real;
Function Getvalue(s:string):Boolean;
begin
result:=true;
if pos('+',s)>0 then
result:=false;
if pos('-',s)>0 then
result:=false;
if pos('*',s)>0 then
result:=false;
if pos('/',s)>0 then
result:=false;
end;
Function GetMyresult(av,bv:real;F:string):string;
begin
try
if f='+' then
result:=floattostr(av+bv)
else if f='-' then
result:=floattostr(av-bv)
else if f='*' then
result:=floattostr(av*bv)
else if (f='/') then
begin
if bv<>0 then
result:=floattostr(av/bv)
else
begin
Result:='ERROR';
exit;
end;
end
else result:='ERROR';
except
result:='ERROR';
end;
end;
begin
try
ipos1:=pos('+',str);
ipos2:=pos('-',str);
ipos3:=pos('*',str);
ipos4:=pos('/',str);
if ipos1>0 then
begin
stra:=leftstr(str,ipos1-1);
strb:=rightstr(str,length(str)-ipos1);
f:='+';
end
else if ipos2>0 then
begin
stra:=leftstr(str,ipos2-1);
strb:=rightstr(str,length(str)-ipos2);
f:='-';
end
else if ipos3>0 then
begin
stra:=leftstr(str,ipos3-1);
strb:=rightstr(str,length(str)-ipos3);
f:='*';
end
else if ipos4>0 then
begin
stra:=leftstr(str,ipos4-1);
strb:=rightstr(str,length(str)-ipos4);
f:='/';
end
else
begin
result:=trim(str);
exit;
end;
if Getvalue(stra) then
valuea:=strtofloat(stra)
else
valuea:=strtofloat(getnum(stra));
if Getvalue(strb) then
valueb:=strtofloat(strb)
else
valueb:=strtofloat(getnum(strb));
result:=GetMyresult(valuea,valueb,f);
except
result:='ERROR';
end;
end;