if not(a in ['+','-','*','/','(',')','#']) or not(b in ['+','-','*','/','(',')','#']) then result:='e'
else
case a of
'+','-': case b of
'*','/','(':result:='';
end;
'*','/':if b='(' then result:='';
'(': if b=')' then result:='=' else if b='#' then result:='e' else result:='';
'#': if b=')' then result:='
函数如下:
unit MyFunction;
![](/Images/OutliningIndicators/None.gif)
interface
![](/Images/OutliningIndicators/None.gif)
//得到四则混合运算的值 ,+-*/()的运算 20030307 by Judy @_@
//修改 maxN设置 表达式的最大输入字符
function GetExpressionValue(s:string):Double;
![](/Images/OutliningIndicators/None.gif)
implementation
![](/Images/OutliningIndicators/None.gif)
uses
Windows, Messages, SysUtils, Classes, Controls, Dialogs,
StdCtrls;
![](/Images/OutliningIndicators/None.gif)
function GetExpressionValue(s: string): Double;
const
maxN=255;
var
res,ch:char;
oprTop,numTop:integer;
opr:array[1..maxN] of char;
num:array[1..maxN] of real;
![](/Images/OutliningIndicators/None.gif)
sTemp:string;
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
procedure error;
begin
//write(fout,'error!');
showmessage('表达式错误,请检查!');
Result :=0;
exit;
end;
function comp(a,b:char):char;
begin
if not(a in ['+','-','*','/','(',')','#']) or not(b in ['+','-','*','/','(',')','#']) then result:='e'
else
case a of
'+','-': case b of
'*','/','(':result:='<';
else result:='>';
end;
'*','/':if b='(' then result:='<' else result:='>';
'(': if b=')' then result:='=' else if b='#' then result:='e' else result:='<';
')': if b='(' then result:='e' else result:='>';
'#': if b=')' then result:='e' else if b='#' then result:='R' else result:='<';
end;
end;
function cal(a,b:real;p:char):real;
begin
case p of
'+': result:=a+b;
'-': result:=a-b;
'*': result:=a*b;
'/': if b=0 then
begin
error;
![](/Images/OutliningIndicators/None.gif)
ShowMessage('[B] - '+sTemp);
![](/Images/OutliningIndicators/None.gif)
result:=0;
end
else result:=a/b;
end;
end;
function GetNumber(var s:string):real;
var
i,code:integer;
begin
i:=1;
while (i<=length(s))and(s[i] in ['0'..'9','.']) do inc(i);
val(copy(s,1,i-1),result,code);
delete(s,1,i-1);
end;
begin
sTemp := s;
![](/Images/OutliningIndicators/None.gif)
opr[1]:='#';
s:=s+'#';
oprTop:=1;
numTop:=0;
res:=' ';
repeat
if s[1] in ['0'..'9'] then
begin
inc(numTop);
num[numTop]:=GetNumber(s);
end
else
begin
ch:=s[1];
delete(s,1,1);
repeat
res:=comp(opr[oprTop],ch);
case res of
'>':begin
num[numTop-1]:=cal(num[numTop-1],num[numtop],opr[oprTop]);
dec(numTop);
dec(oprTop);
end;
'<':begin
inc(oprTop);
opr[oprTop]:=ch;
end;
'=':begin
dec(oprTop);
end;
'e':begin
error;
ShowMessage('[A] - '+sTemp);
result:=0;
exit;
end;
'R':begin
result:=num[numTop];
end;
end;
until res<>'>';
end;
until res='R';
end;
![](/Images/OutliningIndicators/None.gif)
end.
![](/Images/OutliningIndicators/None.gif)