C#數學運算表達式解釋器
測試文件內容:
a=2+3*2;
b=2*(2+3);
浏覽按鈕事件處理程序:
private void button_browse_Click(object sender, EventArgs e)
{
OpenFileDialog fbd = new OpenFileDialog();
fbd.Title = "請選擇一個文件:";
fbd.CheckFileExists = true;
fbd.CheckPathExists = true;
fbd.Filter = "*.txt(文本文件)|*.txt|*.*(所有文件)|*.*";
fbd.FileName = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
textBox_saveDir.Text = fbd.FileName;
try
{
FileStream fs = new FileStream(fbd.FileName, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
analyse(line);
}
}
catch (Exception ex)
{
MessageBox.Show("錯誤:" + ex.Message + "\r\n堆棧:" + ex.StackTrace);
}
}
}
分析一行表達式:
private void analyse(string line)
{
//以分號作為結束符,支持一行內寫多個語句
string[] expA = line.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < expA.Length; i++)
{
analyseExpA(expA[i]);
}
}
計算一條表達式:
private void analyseExpA(string expA)
{
string[] expB = expA.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < expB.Length; i++ )
{
Regex reg = new Regex("[a-zA-Z]");
if (!reg.IsMatch(expB[i]))
{
object obj = EvalExpress(expB[i]);
if (obj != null)
{
textBox1.Text += expA + " = " + obj.ToString() + "\r\n";
}
else
{
textBox1.Text += expA + ",無法識別的表達式\r\n";
}
}
}
}
源碼下載:C#數學運算表達式解釋器源碼
------------------------------------------分割線------------------------------------------
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /2014年資料/7月/17日/C#數學運算表達式解釋器
下載方法見 http://www.linuxidc.com/Linux/2013-07/87684.htm
------------------------------------------分割線------------------------------------------