TYVJ1043(表达式计算4)

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.

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值