我做了一个Infix
toPostfix
转换器,并认为它有效,但是当我回去向我的老师展示它时,他测试的一个例子结果是错误的。:|
如果有人能在这件事上帮助我,我将不胜感激,并让我知道出了什么问题。
我跳过了关于输入数字按钮的部分,只发布了其余部分,
private void button20_Click(object sender, EventArgs e)
{
try
{
string infix = textBox1.Text;
infixTopostfix obj = new infixTopostfix(infix);
textBox1.Text = string.Empty;
Console.WriteLine("{0} is the Postfix of {1}", obj.createPrifex(), infix);
}
catch (Exception e1)
{
Console.WriteLine(e1.ToString());
}
}
上面的部分用于将 a 重定向console.writeline
到我的文本框及其完成所有工作并给出最终结果的按钮。
这是主要课程:
class infixTopostfix
{
public infixTopostfix(string strTemp)
{
strInput = strTemp;
}
private int isOperand(char chrTemp)
{
char[] op = new char[6] { '*', '/', '+', '-', '^', '(' };
foreach (char chr in op)
if (chr == chrTemp)
{
return 1;
}
return 0;
}
private int isOperator(char chrTemp)
{
char[] op = new char[5] { '*', '/', '+', '-', '^' };
foreach (char chr in op)
if (chr == chrTemp)
{
return 1;
}
return 0;
}
private string strResualt = null;
private string strInput = null;
public string createPrifex()
{
int intCheck = 0;
//int intStackCount = 0;
object objStck = null;
for (int intNextToken = 0; intNextToken <= strInput.Length - 1; intNextToken++)
{
intCheck = isOperand(strInput[intNextToken]);
if (intCheck == 1)
stkOperatore.Push(strInput[intNextToken]);
else
if (strInput[intNextToken] == ')')
{
int c = stkOperatore.Count;
for (int intStackCount = 0; intStackCount <= c - 1; intStackCount++)
{
objStck = stkOperatore.Pop();
intCheck = isOperator(char.Parse(objStck.ToString()));
if (intCheck == 1)
{
strResualt += objStck.ToString();
}
}
}
else
strResualt += strInput[intNextToken];
}//end of for(int intNextToken...)
int intCount = stkOperatore.Count;
if (intCount > 0)
{
int c = stkOperatore.Count;
for (int intStackCount = 0; intStackCount <= c - 1; intStackCount++)
{
objStck = stkOperatore.Pop();
intCheck = isOperator(char.Parse(objStck.ToString()));
if (intCheck == 1)
{
strResualt += Convert.ToString(objStck);
}
}
}
return strResualt;
}
private System.Collections.Stack stkOperatore = new System.Collections.Stack();
}
}
这是失败的输入:
A^B^(CD/(E+F))-(G+H)^L*Z+Y
此代码的结果不正确:
ABCDEF+/-^^GH+-LZY+*^
正确的结果:
ABCDEF+/-^^GH+L^Z*-Y+