例如:
1. CalcExpr('2*5+1')='11'
2. 带条件
CalcExpr('2>1&4<=5 : 2*5')='10'
CalcExpr('6<2 : 3')='0'
3. 带函数
CalcExpr('max(1,2,3,6,4+7,7)')='11'
用法:将untCalc.pas 加入到你的工程里面,然后调用CalcExpr即可。
这里是源代码:
unit untJCalc;
interface
uses
classes,sysutils;
type
TJStack=class
private
Lines:TStrings;
public
constructor Create;
destructor Destroy;
procedure init;
procedure push(s:string);
function GetTop:String;
function Pop:String;
end;
TJExpr=class
private
Expr:String;
Position:Integer;
Min,max:Integer;
Eof:Boolean;
public
constructor Create(pExpr:String);
function read:String;
procedure GoFirst;
end;
function CalcExpr(sExpr:String):String;
function CalcExprItem(sOptr,sA,sB:String):String;
function OptrIndex(w:string):Integer;
function GetParamCount(pFunc:String):Integer;
function ExecFunc(pFunc:String;pParam:Array of string;pParamCount:Integer):string;
implementation
constructor TJStack.Create;
begin
inherited Create;
lines:=TStringList.create;
end;
procedure TJStack.init;
begin
lines.free;
end;
destructor TJStack.Destroy;
begin
lines.free;
inherited Destroy;
end;
procedure TJStack.push(s:string);
begin
lines.add(s);
end;
function TJStack.GetTop:String;
begin
if Lines.count>0 then
Result:=lines[lines.count-1]
else
Result:='';
end;
function TJStack.Pop:String;
begin
if Lines.Count>0 then
begin
Result:=GetTop;
lines.delete(lines.count-1);
end
else
Result:='';
end;
//////////////////////TJExpr////////////////
constructor TJExpr.Create(pExpr:String);
begin
Expr:=lowercase(pExpr)+'#';
Min:=1;
Max:=length(Expr);
Position:=1;
Eof:=false;
end;
function TJExpr.read:String;
function SameType(s1,s2:string):boolean;
var
c1,c2:string;
begin
c1:='';c2:='';
if length(s1)>0 then c1:=s1[length(s1)];
if length(s2)>0 then c2:=s2[Length(s2)];
if ((pos(c1,'0123456789.')>0) and (pos(c2,'0123456789.')>0))
then
begin
result:=true;
end
else
begin
Result:=false;
end;
if (c1='-')and(c2='-') then Result:=false;
if s1+s2='>=' then Result:=true;
if s1+s2='<=' then Result:=true;
if s1+s2='<>' then Result:=true;
if pos(s1+s2,'max(')>0 then Result:=true;
if pos('-',s1+s2)>1 then Result:=false;
if (s1='')or(s2='') then result:=true;
end;
begin
if Position<=Max then
begin
Result:=trim(Expr[Position]);
如果您对本文有任何疑问或者建议,请到讨论区发表您的意见:
>>
论坛入口 <<
上一篇:计算出用字符串表示的数学表达式的值 下一篇:鼓励,很多的,Delphi高手突破,外加冷水一瓢
【文章评论】
【收藏本文】
【推荐好友】
【打印本文】
【我要投稿】 【论坛讨论】