您的位置:首页 > 编程语言 > C#

字符串表达式求值 C#实现

2010-08-17 18:49 405 查看
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ExpressionResult1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//建立一个数栈和一个操作符栈
Stack<int> numberStack = new Stack<int>();
Stack<char> operatorStack = new Stack<char>();

private void button1_Click(object sender, EventArgs e)
{
//在表达式前后加开始和结束标识符
string expressin = "#" + textBox1.Text + "#";
bool label = false;//标识是否出现连续的数字字符
foreach (char ch in expressin)
{
if (ch >= '0' && ch <= '9')//数字入栈
{
if (label == true)
{
int temp = numberStack.Pop();
temp = temp * 10 + int.Parse(ch.ToString());
numberStack.Push(temp);
}
else
{
numberStack.Push(int.Parse(ch.ToString()));
label = true;
}
}
else
{
if (operatorStack.Count == 0)//将开始标识符入栈
{
operatorStack.Push(ch);
}
else
{
label = false;
string priority = GetPriority(ch);
while(priority == "outOperator")//操作符出栈,并计算前后两个数
{
int num1 = numberStack.Pop();
int num2 = numberStack.Pop();
char oper = operatorStack.Pop();
int result = GetResult(num1 ,num2 ,oper);
numberStack.Push(result );

priority = GetPriority(ch);
}
if (priority == "inOperator")//操作符进栈
{
operatorStack.Push(ch);
}
else //操作符直接弹出
{
operatorStack.Pop();
}
}
}
}

textBox2.Text = numberStack.Pop().ToString();

}

private string GetPriority(char outChar)//比较栈外和栈内两个操作符的优先级
{
char inChar = operatorStack.Peek();
switch (outChar)
{
case '+':
case '-':
switch (inChar)
{
case '+':
case '-':
case '*':
case '/':
return "outOperator";
case '(':
case '#':
return "inOperator";
}
break;
case '*':
case '/':
switch (inChar)
{
case '+':
case '-':
case '(':
case '#':
return "inOperator";
case '*':
case '/':
return "outOperator";
}
break;
case '(':
return "inOperator";
case ')':
switch (inChar)
{
case '(':
return "abandonOperator";
default :
return "outOperator";
}
case '#':
switch (inChar)
{
case '#':
return "abandonOperator";
default :
return "outOperator";
}
default :
throw new Exception("包含非法字符!");
}
return "";
}

private int GetResult(int num1, int num2, char oper)//根据操作符计算两个数
{
int result = 0;
switch (oper)
{
case '+':
result = num2 + num1;
break;
case '-':
result = num2 - num1;
break;
case '*':
result = num2 * num1;
break;
case '/':
if (num1==0)
{
throw new Exception();
}
result = num2 / num1;
break;
default :
result = 0;
break;
}
return result;

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: