program P1043
var
c:char;
sym:array[0..30]of char;
num:array[0..30]of longint;
ts,tn:shortint;
x:longword;
procedure calcu;
var
p:char;
x,x2:longint;
x1:real;
begin
p:=sym[ts];
dec(ts);
x2:=num[tn];
dec(tn);
x1:=num[tn];
dec(tn);
case p of
'+':x:=trunc(x1)+x2;
'-':x:=trunc(x1)-x2;
'*':x:=trunc(x1)*x2;
'/':x:=trunc(x1) div x2;
'^':x:=trunc(exp(x2*ln(x1)));
end;//case
if tn<0 then inc(tn);
inc(tn);
num[tn]:=trunc(x);
end;
procedure push;
begin
inc(ts);
sym[ts]:=c;
read(c);
end;
begin
assign(input,'P1043.in'); reset(input);
assign(output,'P1043.out'); rewrite(output);
fillchar(num,sizeof(num),0);
ts:=0;
tn:=0;
read(c);
while not eoln do
begin
case c of
'0'..'9':begin
x:=0;
repeat
x:=x*10+ord(c)-ord('0');
read(c);
until not(c in ['0'..'9']);
inc(tn);
num[tn]:=x;//读入完一个数字就加入num。
end;
'+','-':begin
while (ts>0) and (sym[ts]<>'(')do calcu;//出现+或-直到碰到左括号。
push;
end;
'*','/':begin
while (ts>0) and (sym[ts] in ['*','/','^'])do calcu;//出现乘号或除号要求符号必须是*或/才行,因为*和/的优先度要大于+和-。
push;
end;
'^':begin
while (ts>0) and (sym[ts]='^')do calcu;//如果符号是计算乘方就必须要求下一个符号也是乘方,因为乘方的优先级最大。
push;
end;
'(':push;//如果是左括号就放入符号栈中。
')':begin//如果是右括号就计算括号里面的内容。
while (sym[ts]<>'(') do calcu;//直到碰到左括号。
dec(ts);
read(c);//如果是右括号才继续读数。
end;
end;
if c in ['0'..'9'] then//处理最后一个数字。
begin
inc(tn);
num[tn]:=ord(c)-ord('0');
end
else if c=')' then//如果是右括号就再进行计算。
begin
while (sym[ts]<>'(') do calcu;
dec(ts);
read(c);
end;
while sym[ts]='(' do dec(ts);//把多余的左括号都删掉。
while ts>0 do calcu;//如果括号数仍然大于0就再进行计算。
writeln(num[1]);
close(input); close(output);
end.
TYVJ1043(表达式计算4)
最新推荐文章于 2022-02-25 19:38:17 发布