如下:
interface
uses SysUtils;
var
Ca_err:boolean;
Functiondo
_Calculate(s:string):Extended;
implementation
var
Ca_token:char;
Ca_exp:string;
Ca_CurPos,Ca_Len:integer;
function term:Extended;forward;
function factor:Extended;forward;
procedure error;
begin
Ca_err:=true;
raise Exception.Create('错误的表达式!');
end;
function GetNextChar:char;
begin
if Ca_CurPos=Ca_Len then
Result:=#0
else
begin
inc(Ca_CurPos);
Result:=Ca_exp[Ca_CurPos];
end;
end;
procedure match(expectedToken:Char);
begin
if Ca_token=expectedToken then
Ca_token := GetNextChar
else
Ca_err := true;
end;
function exp:Extended ;
var temp:Extended;
begin
if not Ca_err then
begin
temp:=term;
while (Ca_token='+') or (Ca_token='-')do
case (Ca_token) of
'+':begin
match('+');
temp:=temp+term;
end;
'-':begin
match('-');
temp:=temp-term;
end;
end;
//case
Result:=temp;
end;
end;
function term:Extended;
var temp:Extended;
begin
if not Ca_err then
begin
temp:=factor;
while (Ca_token='*') or (Ca_token='/')do
case (Ca_token) of
'*':begin
match('*');
temp:=temp*factor;
end;
'/':begin
match('/');
temp:=temp/factor;
end;
end;
//case
result:=temp;
end;
end;
function FindNum:Extended;
var s:string;
begin
if not Ca_err then
begin
s:=Ca_token;
Ca_token := GetNextChar;
while Ca_token in ['0'..'9']do
begin
s:=s+Ca_token;
Ca_token := GetNextChar;
end;
if Ca_token='.' then
begin
s:=s+'.';
Ca_token := GetNextChar;
while Ca_token in ['0'..'9']do
begin
s:=s+Ca_token;
Ca_token := GetNextChar;
end;
end;
Result:=StrToFloat(s);
if Ca_token='%' then
begin
match('%');
Result:=Result/100;
Ca_token := GetNextChar;
end;
end;
end;
function factor:Extended ;
var temp:Extended;
begin
if not Ca_err then
if Ca_token='(' then
begin
match('(');
temp := exp;
match(')');
end
else
if (Ca_token in ['0'..'9']) then
begin
temp:=FindNum;
end
else
error;
Result:=temp;
end;
Functiondo
_Calculate(s:string):Extended;
begin
Ca_CurPos:=0;
Ca_err:=false;
Ca_exp:=s;
Ca_Len:=length(s);
Ca_token:=GetNextChar;
Result:=exp;
if Ca_CurPos<>Ca_Len then
error;
end;
end.
用法:
Edit2.Text:=FloatToStr(Do_Calculate(Edit1.Text));