function calculateexpress(strexpress:string):string;
VAR
strord:string;
i:integer;
c:char;
ctemp:char;
strnew:string;
Operators:array [0..99] of char;
Operands:array [0..99] ofdo
uble;
Operand:string;
top:integer;
x, y, v:double;
begin
strord:=trim(strexpress);
//判断STRORD只有数字或运算符号
if not isnum(strord) then
begin
calculateexpress:='Invalid Input!';
exit;
end;
//----------------------------
strnew:='';
top:=-1;
for i:=1 to length(strord)do
begin
c:=strord;
case c of
' ': ;
'+','-':begin
while (top>=0)do
begin
ctemp:=Operators[top];top:=top-1;
if ctemp='(' then
begin
top:=top+1;
Operators[top]:=ctemp;
break;//跳出这个while循环
end else
strnew:=strnew+ctemp;
end;
top:=top+1;
Operators[top]:=c;
strnew:=strnew+' ';
end;
'*','/': begin
while (top>=0)do
begin
ctemp:=Operators[top];
top:=top-1;
if ctemp='(' then
begin
top:=top+1;
Operators[top]:=ctemp;
break;//跳出这个while循环
end
else
begin
if (ctemp='+') or (ctemp='-') then
begin
top:=top+1;
Operators[top]:=ctemp;
break;//跳出这个while循环
end
else
strnew:=strnew+ctemp;
end;
end;
top:=top+1;
Operators[top]:=c;
strnew:=strnew+' ';
end;
'(': begin
top:=top+1;
Operators[top]:=c;
strnew:=strnew+' ';
end;
')': begin
while (top>=0)do
begin
ctemp:=Operators[top];
top:=top-1;
if ctemp='(' then
begin
break;//跳出这个while循环
end
else
strnew:=strnew+ctemp;
end;
strnew:=strnew+' ';
end;
else
strnew:=strnew+c ;
end;
end;
//for end
//////////操作符出栈
while (top>=0)do
begin
strnew:=strnew+Operators[top];
top:=top-1;
end;
//////////
/////后缀表达式计算完毕:其结果保存在 strnew 中,接下来,就到其求值
form1.sb.Panels[0].Text:='后缀表达式为: '+strnew ;
//////////计算后缀表达式:开始
top:=-1;
Operand:='';
for i:=1 to length(strnew)do
begin
c:=strnew;
if ((c>='0') and (c<='9')) or (c='.') then
begin
Operand:=Operand+c;
end;
if ((c=' ') or (i=length(strnew))) and (Operand<>'') then
begin
top:=top+1;
Operands[Top]:=strtofloat(Operand);
Operand:='';
end;
if (c='+') or (c='-') or (c='*' ) or (c='/') then
begin
if (Operand<>'') then
begin
top:=top+1;
Operands[Top]:=strtofloat(Operand);
Operand:='';
end;
y:=Operands[Top];//pop 双目运算符的第二操作数 (后进先出)注意操作数顺序对除法的影响
top:=top-1;
x:=Operands[Top];
//pop 双目运算符的第一操作数
top:=top-1;
case c of
'+': v := x + y;
'-': v := x - y;
'*': v := x * y;
'/': begin
if y<>0 then
begin
v := x / y;
// 第一操作数 / 第二操作数 注意操作数顺序对除法的影响
end else
begin
calculateexpress:='Dividend By Zero' ;exit;
end;
end;
else
v := 0;
end;
//end case
top:=top+1;
Operands[Top] := v;//push 中间结果再次入栈
end;
end;
//end for
v := Operands[Top];
//pop 最终结果
top:=top-1;
// showmessage('计算结果为: '+floattostr(v));
//////////计算后缀表达式:结束
result:=floattostr(v);
end;
转一个别人的,传入string的四则表达式,直接出结果!!