111,119
社区成员
发帖
与我相关
我的任务
分享
try
{
string strOpSeparators = @"(\()|(\))|(\+)|(\-)|(\*)|(\/)|(#)";
string[,] strLev = new string[,] { { "(", "1" }, { "+", "2" }, { "-", "2" }, { "*", "3" }, { "/", "3" } };
string strInputOp = this.tbxResult.Text.Trim() + "#";
Regex reOp = new Regex(strOpSeparators);
string[] strSplitOp = reOp.Split(strInputOp);
//判断数字(这里只能判断整数和浮点数)
string strNumber = @"^-?[1-9]\d*$|^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$";
Regex reNumber = new Regex(strNumber);
//判断运算符和一些括号之类的
string strSymbol = @"\(|\)|\+|\-|\*|\/|#";
Regex reSymbol = new Regex(strSymbol);
Stack<string> stJudge = new Stack<string>();
Queue<string> quValue = new Queue<string>();
int intTest = 1;
test:
if (strSplitOp[strSplitOp.Length - intTest] == "")
{
intTest++;
goto test;
}
if (strSplitOp[strSplitOp.Length - intTest] != "#")
{
MessageBox.Show("#");
return;
}
#region 转换
foreach (string s in strSplitOp)//不能处理负数
{
if (s != "" && s != null)
{
if (reNumber.IsMatch(s))//如果是数字直接入队列
{
if (quValue.Count == 0)
{
quValue.Enqueue(s);
}
else
{
string strTest = "";
foreach (string strValueQue in quValue)
{
strTest = strValueQue;
}
if (reNumber.IsMatch(strTest))
{
quValue.Enqueue("&");//在两个连在一起的数字用&分隔
}
quValue.Enqueue(s);
}
}
else
{
if (reSymbol.IsMatch(s))//这里是运算符之类的
{
if (stJudge.Count == 0)//如果是第一个运算符之类的就直接入栈
{
stJudge.Push(s);
}
else
{
if (s == "#")//这里表示转化成逆波兰式已经结束了
{
foreach (string judge in stJudge)
{
quValue.Enqueue(judge);
}
}
else
{
if (s.Equals(")"))
{
PV:
string PopValue = stJudge.Pop();
if (PopValue != "(")
{
quValue.Enqueue(PopValue);
goto PV;
}
else
{
if (PopValue.Equals("("))
{
//什么都不做
}
}
}
else
{
if (s == "(")
{
stJudge.Push(s);
}
else
{
POP:
string strPop = stJudge.Pop();
int vOld = 0;
int vNew = 0;
for (int j = 0; j < strLev.GetLength(0); j++)
{
if (strPop == strLev[j, 0])
{
vOld = Convert.ToInt32(strLev[j, 1]);
}
if (s == strLev[j, 0])
{
vNew = Convert.ToInt32(strLev[j, 1]);
}
}
if (vNew > vOld)//如果新操作符的优先级大的话就进入栈
{
stJudge.Push(strPop);
stJudge.Push(s);
}
else
{
quValue.Enqueue(strPop);//把旧操作符(优先级低)放入队列
if (stJudge.Count > 0)
{
goto POP;
}
else
{
stJudge.Push(s);
}
}
}
}
}
}
}
else
{
MessageBox.Show("标准输入格式,如(10+20)*2");
return;
}
}
}
}
#endregion
//运算结果
Stack<string> stResult = new Stack<string>();
string strRexResult = @"\+|\-|\*|\/";
Regex reResult = new Regex(strRexResult);
foreach (string result in quValue)
{
if (result != "&")
{
if (reResult.IsMatch(result))
{
double dblSencond = Convert.ToDouble(stResult.Pop());
double dblFirst = Convert.ToDouble(stResult.Pop());
double dblResult = 0.0;
switch (result)
{
case "+":
dblResult = dblFirst + dblSencond;
break;
case "-":
dblResult = dblFirst - dblSencond;
break;
case "*":
dblResult = dblFirst * dblSencond;
break;
case "/":
dblResult = dblFirst / dblSencond;
break;
}
stResult.Push(dblResult.ToString());
}
else
{
stResult.Push(result);
}
}
}
foreach (string dblValue in stResult)
{
this.tbxResult.Text = dblValue;
}
}
catch (Exception)
{
MessageBox.Show("输入表达式格式不正确,暂不支持负数的运算!");
}