首页 > 代码库 > C#数学运算表达式解释器
C#数学运算表达式解释器
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#数学运算表达式解释器源码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。