#region 利用datetable的compute指令
//DataTable dt = new DataTable();
//var Result = dt.Compute(textBox1.Text, "");//将运算字符串转换成表达式运算
//label\_Result.Text = Result.ToString();
#endregion
#region 利用栈
Stack<float> s_data = new Stack<float>();
Stack<char> s_opera = new Stack<char>();
String InputExpression = textBox1.Text;
//String InputExpression = "120+205+3\*(4-2)";
int i;
int temp = 0;
int priority(char c) //得到每个符号的优先级
{
int pr = 0;
switch (c)
{
case '+':
case '-': pr = 1; break;
case '\*':
case '/': pr = 2; break;
case '(': pr = 3; break;
case ')': pr = 0; break;
}
return pr;
}
bool is\_digital(char d) //判断是否为数字
{
if (d >= '0' && d <= '9')
return true;
else
return false;
}
void execution() //将数字栈的前两个数字进行运算,并将结果压栈
{
float temp1, temp2;
char operation;
temp2 = s_data.Pop();
temp1 = s_data.Pop();
operation = s_opera.Pop();
switch (operation)
{
case '+':
s_data.Push(temp1 + temp2);
break;
case '-':
s_data.Push(temp1 - temp2);
break;
case '\*':
s_data.Push(temp1 \* temp2);
break;
case '/':
s_data.Push(temp1 / temp2);
break;
}
}
for (i = 0; i < InputExpression.Length; i++)
{
if (is\_digital(InputExpression[i])) //如果字符为数字
{
if (temp == 0)
temp = InputExpression[i] - '0'; //将字符转换为数字
else
temp = temp \* 10 + (InputExpression[i] - '0'); //将数字转换为多位数
if (i == InputExpression.Length - 1) //将末尾的最后一个数字压进数字栈
s_data.Push(temp);
}
else
{
//如果碰到字符了,首先把前一个数字压入数字栈
if (temp != 0)
{
s_data.Push(temp);
temp = 0;
}
if (s_opera.Count == 0) //如果栈s\_opera的元素个数为零
{
s_opera.Push(InputExpression[i]); //把运算符存入栈s\_opera中
}
else //如果栈s\_opera中已经有了运算符
{
int pr_top = priority(s_opera.Peek()); //栈顶运算符的优先级
if ((priority(InputExpression[i]) > pr_top) || (pr_top == 3 && priority(InputExpression[i]) != 0)) //如果当前运算符优先级大于栈顶运算符,或者栈顶运算符优先级为3且当前运算符优先级不为0
s_opera.Push(InputExpression[i]); //将当前运算符存入栈s\_opera中
else if (pr_top == 3 && priority(InputExpression[i]) == 0) //当右括号遇到左括号
{
s_opera.Pop();
continue; //考虑下一个字符
}
else
{
execution();
i = i - 1;
}
}
}
}
for (int j = s_opera.Count; j > 0; j--)
{
execution();
}
Result.Text = Convert.ToString(s_data.Pop());
#endregion
#region 利用递归
//DataTable dt = new DataTable();
//var Result = dt.Compute(textBox1.Text, "");//将运算字符串转换成表达式运算
//label\_Result.Text = Result.ToString();
#endregion
}
}
}
另外还有一种简单的方法,就是利用datetable的compute指令,代码如下:
DataTable dt = new DataTable();
var Result = dt.Compute(textBox1.Text, “”);//将运算字符串转换成表达式运算
label_Result.Text = Result.ToString();