PDA

View Full Version : تبدیل postfix به infix



parva-88
پنج شنبه 02 دی 1389, 11:22 صبح
من کد پایین رو نوشتم و برنامه هم اجرا میشه ولی runtime err داره توی تابع predicatesh کسی میتونه بگه erroresh چیه؟


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace postfix
{
class Program
{
static void Main(string[] args)
{
string infix, postfix = "";
Console.WriteLine("enter your infix:");
infix = Console.ReadLine();
change(infix,postfix);
Console.Read();
}
static bool num(string n)
{
if(n.CompareTo("0")>=0 && n.CompareTo("9")<=0)
return true;
else
return false;
}
static bool predicate(string op1, string op2)
{
int p1, p2;
string opstring = "(+-*/%";
int[] isp = {0, 0, 12, 12, 13, 13, 13 };
p1=opstring.IndexOf(op1);
p2=opstring.IndexOf(op2);
if (isp[p1] >= isp[p2])
return true;
return false;
}


static void change(string infix,string postfix)
{

string symbol, topsymbol;
Stack opstack = new Stack();
for (int i = 0; i <= infix.Length; i++)//barrasie kolle reshte
{
symbol = infix.Substring(i, 1);
if (num(symbol))
{
postfix += symbol;
}
if (symbol == "(")
{
opstack.Push(symbol);
}
else if (symbol == ")")
{
topsymbol = (string)opstack.Pop();
while (topsymbol != "(")
{
postfix += topsymbol;
topsymbol =(string)opstack.Pop();
}//while
}

else{//operand
if(opstack.Count==0|| (!predicate((string)opstack.Peek(),symbol)))
opstack.Push(symbol);
else{
topsymbol=(string)opstack.Pop();
while(predicate(topsymbol,symbol))
{
postfix+=topsymbol;
if(opstack.Count==0)

break;

topsymbol=(string)opstack.Pop();
}//end wjile
opstack.Push(symbol);
}//for
}//else
}//else
while(opstack.Count>0)
{
topsymbol=(string)opstack.Pop();
postfix+=topsymbol;
}//end while
Console.WriteLine("postfix is:"+postfix);

}
}


}

hadi-z
پنج شنبه 02 دی 1389, 18:00 عصر
سلام
فکر کنم اینجا کمکتون کنه:

http://www.dreamincode.net/forums/topic/37428-converting-and-evaluating-infix-postfix-and-prefix-expressions-in-c/