تبدیلات Infix به Postfix و محاسبه نتیجه در زبان پاسکال

the_king

مدیرکل انجمن
کد زیر پس از تبدیل معادله Infix به Postfix، نتیجه را محاسبه و اعلام می کند :

کد:
program prg;
uses crt;
var
	x:integer;
	infix:string;
	stack:array[1..50] of longint;
	postfix:array[1..50] of longint;
	equation:longint;
	postfixi:integer;
	stacki,i,j,k:integer;
function power(a,b:integer):integer;
var
	i,j:integer;
begin
	j:=1;
	for i:=1 to b do
		j:=j*a;
	power:=j;
end;

function pop:integer;
begin
	pop:=stack[stacki];
	if stacki<1 then pop:=32750
	else stacki:=stacki-1;
end;

procedure push(a:integer);
begin
	stacki:=stacki+1;
	stack[stacki]:=a;
end;

begin
	clrscr;
	postfixi:=1;
	write (' Equation : ');
	readln (infix);
	write (' x :');
	readln (x);
	i:=1;
	infix:='('+infix+')';
	while (i<=length(infix)) do
	begin
		if ((infix[i]>='0') and (infix[i]<='9')) then
		begin
			j:=ord(infix[i])-48;
			while ((infix[i+1]>='0') and (infix[i+1]<='9')) do
			begin
				i:=i+1;
				j:=j*10+ord(infix[i])-48
			end;
			postfix[postfixi]:=j;
			postfixi:=postfixi+1;
		end 
		else begin
			case infix[i] of
				'x': begin
					 postfix[postfixi]:=x;
					postfixi:=postfixi+1;
				end;
				'-': begin
					k:=pop;
					if (k<32756) then
					begin
						push(32751);
						postfix[postfixi]:=k;
						postfixi:=postfixi+1;
					end
					else begin
						push(k);
						push(32751);
					end;
				end;
				'+': begin
					k:=pop;
					if (k<32756) then
					begin
						push(32752);
						postfix[postfixi]:=k;
						postfixi:=postfixi+1;
					end
					else begin
						push(k);
						push(32752);
					end;
				end;
				'/': begin
					k:=pop;
					if (32752<k) and (k<32756) then
					begin
						push(32753);
						postfix[postfixi]:=k;
						postfixi:=postfixi+1;
					end
					else begin
						push(k);
						push(32753);
					end;
				end;
				'*': begin
					k:=pop;
					if (32752<k) and (k<32756) then
					begin
						push(32754);
						postfix[postfixi]:=k;
						postfixi:=postfixi+1;
					end
					else begin
						push(k);
						push(32754);
					end;
				end;
				'^': push(32755);
				'(': push(32756);
				')': begin
					k:=pop;
					while (k<32756) do
					begin
						postfix[postfixi]:=k;
						postfixi:=postfixi+1;
						k:=pop;
					end;
				end;
			end;
		end;
		i:=i+1;
	end;
	for i:=1 to postfixi-1 do
	begin
		if postfix[i]<32750 then
			push(postfix[i])
		else begin
			k:=pop;
			j:=pop;
			case postfix[i] of
				32751 : push(j-k);
				32752 : push(j+k);
				32753 : push(j div k);
				32754 : push(j*k);
				32755 : push(power(j,k));
			end;
		end;
	end;
	equation:=pop;
	writeln (' y = ',equation);
end.
 

جدیدترین ارسال ها

بالا