type
tovs=record
ovs:array[1..100] of real
end;
function jxbds(zifu:string;var td:tovs):boolean;
const max=100;
op_set:set of char=['+','-','*','/'];
letter:set of char=['A'..'Z','a'..'z','0'..'9','.'];
var
f:array['#'..'/','#'..'/'] of shortint;
temp,i,top1,top2:integer;
t:real;
p:string;
ops:array[1..100] of char;
begin
top1:=0;
f['+','+']:=1; f['+','-']:=1; f['+','*']:=-1; f['+','/']:=-1;
f['+','(']:=-1; f['+',')']:=1; f['+','#']:=1;
f['-','+']:=1; f['-','-']:=1; f['-','*']:=-1; f['-','/']:=-1;
f['-','(']:=-1; f['-',')']:=1; f['-','#']:=1;
f['*','+']:=1; f['*','-']:=1; f['*','*']:=1; f['*','/']:=1;
f['*','(']:=-1; f['*',')']:=1; f['*','#']:=1;
f['/','+']:=1; f['/','-']:=1; f['/','*']:=1; f['/','/']:=1;
f['/','(']:=-1; f['/',')']:=1; f['/','#']:=1;
f['(','+']:=-1; f['(','-']:=-1; f['(','*']:=-1; f['(','/']:=-1;
f['(','(']:=-1; f['(',')']:=0; f['(','#']:=2;
f[')','+']:=2; f[')','-']:=2; f[')','*']:=2; f[')','/']:=2;
f[')','(']:=2; f[')',')']:=2; f[')','#']:=2;
f['#','+']:=-1; f['#','-']:=-1; f['#','*']:=-1; f['#','/']:=-1;
f['#','(']:=-1; f['#',')']:=2; f['#','#']:=0;
if (zifu[1]='-')or(zifu[1]='+') then zifu:='0'+zifu;
for i:=1 to length(zifu) do
if zifu[i]=' ' then zifu:=copy(zifu,1,i-1)+copy(zifu,i+1,length(zifu)-i);
for i:=1 to length(zifu) do
begin
if (zifu[i]='-')and(zifu[i-1]='(') then
zifu:=copy(zifu,1,i-1)+'0'+copy(zifu,i,length(zifu)+1-i);
end;
zifu:=zifu+'#';
top2:=1;ops[top2]:='#';
for i:=1 to length(zifu) do
begin
if zifu[i] in letter then begin
p:=p+zifu[i];
if not(zifu[i+1] in letter) then
begin top1:=top1+1;val(p,t,temp);td.ovs[top1]:=t;p:='';end;
end
else begin
while f[ops[top2],zifu[i]]=1 do
begin
case ops[top2] of
'+':td.ovs[top1-1]:=td.ovs[top1-1]+td.ovs[top1];
'-':td.ovs[top1-1]:=td.ovs[top1-1]-td.ovs[top1];
'*':td.ovs[top1-1]:=td.ovs[top1-1]*td.ovs[top1];
'/':if td.ovs[top1]=0 then
begin
writeln('div by zero!');halt;
end else
td.ovs[top1-1]:=td.ovs[top1-1]/td.ovs[top1];
end;
top1:=top1-1;
top2:=top2-1;
end;
if f[ops[top2],zifu[i]]=-1 then begin top2:=top2+1;ops[top2]:=zifu[i];end;
if top2>1 then
if f[ops[top2],zifu[i]]=0 then top2:=top2-1;
end;
end;
result:=true;
end;
//测试代码:
procedure TForm1.Button1Click(Sender: TObject);
var
s:string;
td:tovs;
begin
s:='3+5*8/(4-5)-3/7+(5*(6-3))';
jxbds(s,td);
showmessage(floattostr(td.ovs[1]));
end;
帖子浏览
|
用户名:学生 用户ID:110 用户级别:9名动江湖 注册时间:2008-09-17 论坛分数:18860 |
贴一段能够计算表达式的函数 :
|
本主题讨论树
-
贴一段能够计算表达式的函数 :
(2652字)
【学生】
2009-02-12 21:10
阅读:14
- 虽然有这个为基础 但是计算24点 还是一点头绪都没有 手头抄录了网上的一段代码 可是重复的太多 又没想好如何过滤重复的 (空) 【学生】 2009-02-12 21:12 阅读:3
-
我后来想到了,24点不用直接计算文本表达式,绕弯子了。
(空)
【夜的影子】
2009-02-12 21:58
阅读:3
- 数据已知,运算符号已知,次数已知,转成文本表达式就绕远了,可以直接在循环中计算。 (空) 【夜的影子】 2009-02-12 21:59 阅读:2
- 表达式的定义: expression = (expression|number) operator (expression|number) (空) 【学生】 2009-02-13 11:13 阅读:4
回复本帖
请先 登录,再回复本帖。