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"; } } } }