而且就一个函数。 但有一个缺点就是不能扩展,就是扩展更高级的运算符很难。 我采用的递归算法,没有自己建立栈,所以代码不多。 function Calculator(var calstr: pchar): double; Function Getoperatenum:double; //取操作数 var temp:pchar; begin temp:=calstr; result:=0; if calstr^='(' then begin Result:=calculator(calstr); exit; end; while ((calstr^>='0')and(calstr^<='9'))or (calstr^='.') do inc(calstr); result:=strtofloat(copy(temp,0,calstr-temp)); end; Function Getoperater:byte; //运算类型 begin if calstr^='(' then //支持 n(n) 这种省去 * 的格式 Result:=ord('*') else begin result:=ord(calstr^); inc(calstr); end; end; var operateNum:Double; begin operateNum:=0; result:=0; while calstr^='(' do inc(calstr); result:=Getoperatenum; while (calstr^<>#0) or (calstr^<>')') do begin case Getoperater of ord('+'):result:=result+calculator(calstr); ord('-'):result:=result-calculator(calstr); ord('*'):result:=result*Getoperatenum; ord('/'): begin operateNum:=Getoperatenum; if operateNum<>0 then result:=result/operateNum else begin showmessage('公式格式错误'); abort; end; end else exit; end; end; if calstr=')' then inc(calstr); end;