bawang51吧 关注:31贴子:3,169
  • 2回复贴,共1

【字符串】表达式求值

只看楼主收藏回复

var dig:array[1..100]of longint;
sym:Array[1..100]of char;
i,k,t,l,l1,l2:longint;
s:string;
function happy(x,y:longint;c:char):longint;
var i:longint;
begin
case c of
'+':exit(x+y);
'-':exit(x-y);
'*':exit(x*y);
'/':exit(x div y);
'^':
begin
happy:=1;
for i:=1 to y do
happy:=happy*x;
exit(happy);
end;
end;
end;
function level(c:char):longint;
begin
case c of
'+','-':exit(1);
'*','/':exit(3);
'^':exit(5);
'(':exit(0);
end;
end;
begin
readln(s);
read(t);
l:=length(s);
i:=1;
while i<=l do
begin
if s[i]='(' then
begin
l1:=l1+1;
sym[l1]:=s[i];
end;
if s[i]=')' then
begin
while sym[l1]<>'(' do
begin
k:=happy(dig[l2-1],dig[l2],sym[l1]);
l2:=l2-1;
dig[l2]:=k;
l1:=l1-1;
end;
l1:=l1-1;
end;
if s[i]='a' then
begin
l2:=l2+1;
dig[l2]:=t;
end;
if s[i] in['0'..'9'] then
begin
k:=ord(s[i])-48;
i:=i+1;
while s[i] in ['0'..'9'] do
begin
k:=k*10+ord(s[i])-48;
i:=i+1;
end;
l2:=l2+1;
dig[l2]:=k;
i:=i-1;
end;
if s[i] in['+','-','*','/','!'] then
begin
if (l1<>0) and (level(s[i])<=level(sym[l1])) then
begin
k:=happy(dig[l2-1],dig[l2],sym[l1]);
l1:=l1-1;
l2:=l2-1;
dig[l2]:=k;
end;
l1:=l1+1;
sym[l1]:=s[i];
end;
i:=i+1;
end;
while l1>0 do
begin
k:=happy(dig[l2-1],dig[l2],sym[l1]);
l2:=l2-1;
l1:=l1-1;
dig[l2]:=k;
end;
writeln(dig[l2]);
end.



IP属地:上海1楼2011-11-01 21:30回复
    输入格式
    a+(a-1)*a/2+5
    3
    输出格式
    11


    IP属地:上海2楼2011-11-01 21:31
    回复
      2025-05-14 04:00:12
      广告
      用了后缀表达式,dig存数字,sym存符号


      IP属地:上海3楼2011-11-01 21:33
      回复