如何求得string类型的计算公式的值?(200分)

  • 主题发起人 轩辕居士
  • 开始时间

轩辕居士

Unregistered / Unconfirmed
GUEST, unregistred user!
给你一个String类型的计算公式,例如:(3+8)/(3+(90-7)/4)*8,怎么把它的值求出来然后转化到float型?
 
如下:
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));
 
最简单的方法是用SQL 服务器帮你算了
呵呵,没比这更简单了
 
谢谢两位对此问题做出的精彩回答,Benlei兄弟的回答详尽而且方便,只要编译成单元文件
就可以调用。火龙真人的回答也不失为一种好办法,而且不用自己动手。两位都是行家,以
后多多指点小弟。再次感谢!我为Benlei加上125分,火龙真人75分。欢迎访问我们的网站
http://www.free7ren.com,QQ:5846677,对我们的工作进行指导![:)]
 
以后有问题还要请教两位!
 

Similar threads

S
回复
0
查看
949
SUNSTONE的Delphi笔记
S
S
回复
0
查看
770
SUNSTONE的Delphi笔记
S
D
回复
0
查看
707
DelphiTeacher的专栏
D
D
回复
0
查看
728
DelphiTeacher的专栏
D
S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
顶部